You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Cloud Gateway为何忽略application.properties中配置的CORS属性?

解决Spring Gateway+CORS+OAuth2资源服务的跨域问题

你的问题核心是OPTIONS预检请求被Spring Security拦截返回401,导致浏览器无法获取CORS响应头,进而触发跨域错误。Postman不会自动发送预检请求,所以能正常访问;而Angular作为浏览器端会先发起OPTIONS预检,这就是两者的差异所在。

解决步骤

1. 修改SecurityConfig,放行OPTIONS预检请求

预检请求不会携带JWT令牌,必须允许其无认证通过。在authorizeExchange中添加对所有OPTIONS请求的放行规则:

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity serverHttpSecurity) {
        serverHttpSecurity
                .authorizeExchange(exchange ->
                        exchange.pathMatchers("/eureka/**")
                                .permitAll()
                                // 放行所有OPTIONS预检请求
                                .pathMatchers(HttpMethod.OPTIONS, "/**")
                                .permitAll()
                                .anyExchange()
                                .authenticated())
                .cors()
                .and()
                .csrf()
                .disable()
                .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt);
        return serverHttpSecurity.build();
    }
}

2. 让CORS配置与Spring Security协同生效

Spring Security的cors()会优先使用CorsConfigurationSource,可以显式定义该Bean复用你的全局规则,避免配置冲突:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    // 生产环境建议指定具体前端域名,不要用*
    configuration.setAllowedOriginPatterns(Collections.singletonList("*"));
    configuration.setAllowedHeaders(Collections.singletonList("*"));
    configuration.setAllowedMethods(Collections.singletonList("*"));
    // 若前端需要传递Cookie等凭证,需开启此项
    configuration.setAllowCredentials(true);
    
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

3. 验证效果

重启网关服务后,Angular发起的OPTIONS预检请求会先通过Security放行,网关的CORS配置会自动添加Access-Control-Allow-Origin等响应头,后续的GET请求就能正常携带JWT令牌完成认证。

额外注意事项

  • 生产环境禁止使用*作为允许来源,应指定前端具体域名(如https://your-angular-app.com),降低安全风险。
  • 如果前端需要传递Cookie或认证凭证,除了后端设置AllowCredentials=true,前端请求也要配置withCredentials: true(Angular中在HttpClient请求时设置)。

内容的提问来源于stack exchange,提问作者LucaT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:35:27