Spring Boot API Gateway对接Angular时的CORS配置问题
Spring Boot API Gateway CORS问题解决指南
问题根源
Angular端触发的CORS错误,是浏览器同源策略拦截了跨域请求导致的——你的API Gateway没有返回符合要求的CORS响应头,浏览器因此拒绝接收响应。
网关添加CORS配置
你的SecurityConfig里缺少CORS相关配置,WebFlux Security会覆盖默认CORS设置,必须在安全过滤链中显式配置:
修改后的完整配置代码:
@Configuration @EnableWebFluxSecurity public class SecurityConfig { @Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity serverHttpSecurity) { return serverHttpSecurity .csrf(ServerHttpSecurity.CsrfSpec::disable) // 注入CORS配置 .cors(cors -> cors.configurationSource(corsConfigSource())) .authorizeExchange(exchange -> exchange .pathMatchers("/eureka/**","/users/add-user") .permitAll() .anyExchange().authenticated() ) .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults())) .build(); } // 自定义CORS规则 private CorsConfigurationSource corsConfigSource() { CorsConfiguration corsConfig = new CorsConfiguration(); // 替换成你的Angular前端实际域名,比如http://localhost:4200 corsConfig.addAllowedOrigin("http://localhost:4200"); // 允许所有HTTP请求方法 corsConfig.addAllowedMethod("*"); // 允许所有请求头 corsConfig.addAllowedHeader("*"); // 允许携带凭证(如JWT、Cookie) corsConfig.setAllowCredentials(true); // 暴露前端需要读取的响应头,比如Authorization corsConfig.addExposedHeader("Authorization"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 对所有路径应用该CORS规则 source.registerCorsConfiguration("/**", corsConfig); return source; } }
关键配置说明
- 不要用
*作为allowedOrigin同时开启allowCredentials,浏览器会直接报错,必须指定具体的前端域名。 - 如果前端请求需要携带凭证(比如带JWT的请求头),一定要开启
setAllowCredentials(true),同时Angular请求要设置withCredentials: true。 addExposedHeader用来暴露前端需要获取的自定义响应头,比如登录后的token头。
CORS配置范围答疑
只需要在API Gateway中配置一次,不需要每个微服务都配:
- 前端所有请求都是直接打给网关,网关作为统一入口处理跨域,返回CORS响应头即可。
- 微服务之间属于内部调用,不受浏览器同源策略限制,完全不需要配置CORS。
只有当微服务被前端直接访问(绕过网关)时,才需要在对应微服务里加CORS配置,你的场景不涉及这种情况。
内容的提问来源于stack exchange,提问作者Khalil Hermassi
相关产品推荐
相关产品推荐

