Vue + spring boot + spring security 跨域訪問

本文主要介紹在項目中用到前端Vue 技術,後端spring boot  + spring security權限框架,在vue頁面中使用Ajax請求後端數據,後臺響應並返回結果。具體配置如下:

Vue前端技術

ajaxPost('地址','參數',res =>{})該塊依個人寫法不同,名稱自己編寫。前端Vue頁面登錄請求後臺時,

參數傳遞用戶名密碼格式:'username=admin1&password=111111'

主要介紹後端配置情況,首先在SpringMVC的配置類中

class WebMvcConfig extends WebMvcConfigurerAdapter配置addCorsMappings方法,該方法是處理跨域請求
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("*","http://localhost:8001/")//Vue 項目的服務地址和端口號 可用*號代替
            .allowCredentials(true)
            .allowedMethods("GET", "POST", "DELETE", "PUT")
            .maxAge(3600);
}

然後在Security的配置類中 WebSecurityConfig extends WebSecurityConfigurerAdapter放過 option 請求,讓Spring security 不校驗preflight request 。

protected void configure(HttpSecurity http) throws Exception {
    //設置option
    http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll(); //放過 option 請求

}

到此配置完畢。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章