Spring框架CORS跨域报错No 'Access-Control-Allow-Origin'如何解决
问题根因
- 你使用了Spring Security + OAuth2 ResourceServer组合架构,ResourceServer的过滤器链优先级默认远高于WebSecurityConfigurerAdapter的过滤器链,你仅在WebSecurity配置中开启
http.cors()不会生效,CORS预检OPTIONS请求会优先进入ResourceServer的拦截逻辑,而ResourceServer默认未开启CORS支持,也未放行OPTIONS请求,导致预检请求被直接拦截,无法返回正确的跨域响应头。 - 你编写的两个CORS配置类同名,会产生类冲突导致其中一个配置不生效;另外WebMvc层的CORS配置优先级低于Spring Security过滤器链,无法生效;自定义的CorsFilter虽然设置了高优先级,但如果Spring Security过滤器链先拦截了预检请求,仍然不会返回跨域头。
解决方案
1. 清理重复配置
删除之前编写的两个同名Cors配置类,避免类冲突,统一使用Spring Security体系内的CORS配置。
2. 调整ResourceServer配置
修改ResourceServerConfig类,开启CORS支持并放行所有OPTIONS预检请求:
@Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http // 开启CORS支持,会自动读取容器中的CorsConfigurationSource配置 .cors() .and() .authorizeRequests() // 放行所有CORS预检请求 .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() .antMatchers(HttpMethod.GET, "/api/informationWS").permitAll() .antMatchers(HttpMethod.POST, "/api/work").authenticated() .anyRequest().denyAll(); } }
3. 注册全局CORS规则
新增CORS配置类,注册全局跨域规则Bean,Spring Security的cors()组件会自动读取该配置:
@Configuration public class CorsConfig { @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration corsConfig = new CorsConfiguration(); // 允许的前端源 corsConfig.setAllowedOrigins(Arrays.asList("http://localhost:4200")); // 允许的请求方法 corsConfig.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许的请求头 corsConfig.setAllowedHeaders(Arrays.asList("*")); // 允许携带Cookie等凭证 corsConfig.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 规则作用于所有接口 source.registerCorsConfiguration("/**", corsConfig); return source; } }
完成上述配置后重启服务即可解决跨域问题。
内容的提问来源于stack exchange,提问作者Pedrojdi
相关产品推荐
相关产品推荐

