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

Spring Boot 3 OAuth2资源服务器迁移后CORS问题求助

Spring Boot 3.0.4 OAuth2资源服务器CORS问题排查与解决

问题原因分析

Spring Boot 3.0.x对应的Spring Security版本为6.x,相比5.8版本,CORS预检请求(OPTIONS)的处理逻辑发生了变化:

  • 6.x版本中,anyRequest().authenticated()会默认拦截所有请求(包括OPTIONS预检请求),而浏览器发起跨域请求时会先发送不带认证token的OPTIONS请求,这直接导致认证拦截触发CORS错误。
  • 5.8版本中对OPTIONS请求有默认放行逻辑,因此升级到Spring Boot 3后该逻辑不再生效。

解决办法

方案1:在安全配置中明确放行OPTIONS请求

修改SecurityFilterChain配置,在认证规则前添加OPTIONS请求的放行规则,确保预检请求能正常通过:

import org.springframework.http.HttpMethod;
// 其他必要导入

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

    http
        .cors(cors -> cors.configurationSource(request -> {
            CorsConfiguration cors = new CorsConfiguration();
            cors.setAllowedOrigins(List.of("http://localhost:8080"));
            cors.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
            cors.setAllowedHeaders(List.of("*"));
            cors.setAllowCredentials(true);
            // 若前端需要读取响应头(如Authorization),需添加暴露配置
            cors.setExposedHeaders(List.of("Authorization"));
            return cors;
        }))
        .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest().authenticated()
        )
        .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt.jwtAuthenticationConverter(getJwtAuthenticationConverter()))
        )
        .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

    return http.build();
}

方案2:独立配置CorsConfigurationSource Bean

将CORS配置抽离为独立Bean,让Spring Security自动识别并使用,这种方式更符合Spring Boot 3的配置规范:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(List.of("http://localhost:8080"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(List.of("*"));
    configuration.setAllowCredentials(true);
    configuration.setExposedHeaders(List.of("Authorization"));
    
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

// 安全配置简化为
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .cors(Customizer.withDefaults()) // 自动使用上述CorsConfigurationSource
        .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest().authenticated()
        )
        .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt.jwtAuthenticationConverter(getJwtAuthenticationConverter()))
        )
        .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

    return http.build();
}

验证步骤

  1. 重启Spring Boot后端服务
  2. 前端发起跨域请求,检查浏览器控制台是否仍存在CORS错误
  3. 若仍有问题,可通过浏览器开发者工具查看OPTIONS请求的响应状态码,确认是否返回200

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:52:40