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

Spring Boot升级后PUT请求遭CORS拦截问题求助

问题解决:Spring Boot 3.1.2升级后PUT请求CORS拦截问题

核心问题分析

你遇到的情况是Spring Boot升级到3.x后,UI端PUT请求触发CORS拦截,但Postman正常、其他请求方法无问题。本质是Spring Security 6.x的CORS配置逻辑变化,以及UI端预检请求(OPTIONS)的处理和全局配置未正确关联导致的。

解决方案步骤

1. 修复SecurityFilterChain的CORS关联

Spring Boot 3.x(基于Spring Security 6)中,必须在SecurityFilterChain Bean里显式启用CORS配置,否则你定义的CorsConfigurationSource不会生效。

修改你的WebSecurityConfiguration,添加CORS启用逻辑:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        // 显式关联自定义CORS配置源
        .cors(cors -> cors.configurationSource(corsConfigurationSource()))
        // 保留你的其他安全配置(如csrf、权限控制等)
        .csrf(csrf -> csrf.disable())
        .authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
    return http.build();
}

// 调整为Spring 6推荐的CORS配置写法
@Bean
CorsConfigurationSource corsConfigurationSource() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration configuration = new CorsConfiguration();
    
    // Spring 6推荐用allowedOriginPatterns替代allowedOrigins,避免*与allowCredentials冲突
    configuration.setAllowedOriginPatterns(Collections.singletonList("*"));
    // 明确包含PUT方法
    configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    configuration.setAllowedHeaders(Collections.singletonList("*"));
    // 若UI端无需携带凭证(如Cookie),建议设为false,避免与* origin规则冲突
    configuration.setAllowCredentials(false);
    
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

2. 移除冲突的重复配置

  • 暂时去掉Controller上的@CrossOrigin注解,避免全局配置与局部配置冲突。
  • 删除额外添加的CrossOriginConfig类:Spring Security的CORS配置优先级高于Spring MVC,重复配置会导致规则逻辑混乱。

3. 验证UI端请求细节

Postman正常是因为它不会触发浏览器的预检请求(OPTIONS),而UI端的PUT请求属于非简单请求,浏览器会先发送OPTIONS预检请求,只有预检通过才会发送实际的PUT请求。

检查UI端请求:

  • 是否携带自定义请求头?如果有,确保CORS配置的allowedHeaders包含这些头(或用*覆盖)。
  • 是否设置了withCredentials: true?如果是,必须将allowedOriginPatterns改为具体的origin(如http://localhost:9500),不能用*,同时将allowCredentials设为true:
    configuration.setAllowedOriginPatterns(Collections.singletonList("http://localhost:9500"));
    configuration.setAllowCredentials(true);
    

为什么之前的配置无效?

  • Spring Security 6.x不再自动应用CorsConfigurationSource,必须在SecurityFilterChain中显式关联。
  • 旧版本的addAllowedOrigin("*")在Spring 6中已过时,推荐用setAllowedOriginPatterns,否则可能导致CORS规则解析异常。
  • 同时存在Spring MVC和Spring Security的CORS配置时,Security的配置优先生效,但未正确关联时规则不会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:15:01