Spring Security如何解决跨域问题?
作者:
rfx
,
2022-10-05 21:19:53
,
所有人可见
,
阅读 255
- 一般的配置cors跨域的方式不适用于spring security框架,因为spring security会修改一些表头,导致我们添加的过滤器不生效,所以必须要使用spring security特殊的方法来处理跨域问题
- 打开跨域,配置springsecurity的配置类
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(corsConfigurationSource());
}
- corsConfigurationSource方法
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:8081", "http://localhost:8080"));
corsConfiguration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}