Spring Boot 1.5.3集成Swagger PUT请求遇CORS无效请求问题求助
解决Spring Boot 1.5.3中PUT请求的CORS问题
针对你遇到的PUT请求报Invalid CORS request的问题,结合Spring Boot 1.5.x和Spring Security的特性,可按以下步骤调整配置:
1. 确保Spring Security启用CORS支持
Spring Security会优先拦截请求,因此必须在安全配置类中显式启用CORS,并关联你的全局CORS配置:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CorsConfigurationSource corsConfigurationSource; @Override protected void configure(HttpSecurity http) throws Exception { // 启用CORS并关联配置源 http.cors().configurationSource(corsConfigurationSource) .and() // 允许OPTIONS预检请求无需认证(非简单请求如PUT会先发OPTIONS) .authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 其他安全规则配置... .anyRequest().authenticated(); } }
2. 修正全局CORS配置(适配带Cookie的请求)
你的原配置中使用*作为允许的Origin,但当请求携带Cookie时,浏览器不允许通配符Origin与allowCredentials=true共存。需调整如下:
@Configuration public class CorsConfig { @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); // 替换为实际需要允许的前端域名(比如Swagger UI的地址、你的业务前端地址) configuration.setAllowedOrigins(Arrays.asList( "http://localhost.mycompany.com:8080", "http://example.com" )); // 明确允许所有HTTP方法,包括PUT configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许携带Cookie(对应请求中的Cookie头) configuration.setAllowCredentials(true); // 允许必要的请求头,覆盖默认配置 configuration.setAllowedHeaders(Arrays.asList( "Origin", "Accept", "Content-Type", "Cookie", "Authorization" )); // 暴露需要前端访问的响应头(可选) configuration.setExposedHeaders(Arrays.asList("Authorization")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
3. 移除Controller上的@CrossOrigin注解
全局CORS配置与局部@CrossOrigin注解可能产生冲突,统一使用全局配置即可,删除PUT端点上的@CrossOrigin。
4. 验证配置效果
重新启动应用后,用curl测试PUT请求:
curl -i -X PUT 'http://localhost.mycompany.com:8080/mom/749f4f1f-0769-488d-9776-17fc3927cfc6/description?description=WangoTango' \ -H 'Origin: http://example.com' \ -H 'Cookie: a.token_key=redacted' \ -H 'accept: application/json'
此时应返回200或业务对应的响应码,而非403。
内容的提问来源于stack exchange,提问作者Bob Kuhar
相关产品推荐
相关产品推荐

