SpringSecurity如何配置跨域訪問
更新時間:2024年08月22日 09:08:45 作者:chinoukin
這篇文章主要介紹了SpringSecurity如何配置跨域訪問方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
說明
java后端web服務有很多種方法可以實現(xiàn)跨域訪問,配置很簡單,今天這里我們用SpringSecurity的方式配置跨域訪問
配置方法如下:
package com.wisea.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
其他
看網(wǎng)上的配置里會有代碼如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
...
}實際上并不起什么作用,總結,當工程中開啟了@EnableWebSecurity的時候,我們只需要讓spring容器中存在一個CorsFilter的跨域過濾器即可。
some days 幾天發(fā)現(xiàn)問題:
當請求的中有redirect時,上面這段代碼就必須了。
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
MyBatis使用<foreach>標簽like查詢報錯解決問題
這篇文章主要介紹了MyBatis使用<foreach>標簽like查詢報錯解決問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
JAVA Iterator接口與增強for循環(huán)的實現(xiàn)
這篇文章主要介紹了JAVA Iterator接口與增強for循環(huán)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11
Java?中很好用的數(shù)據(jù)結構(你絕對沒用過)
今天跟大家介紹的就是?java.util.EnumMap,也是?java.util?包下面的一個集合類,同樣的也有對應的的?java.util.EnumSet,對java數(shù)據(jù)結構相關知識感興趣的朋友一起看看吧2022-05-05

