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

Spring Boot对接Next.js前端时CORS错误配置求助

Spring Boot Security CORS配置问题:浏览器请求失败但Postman正常

Access to XMLHttpRequest at 'http://localhost:8081/api/v1/auth/login' from origin 'http://localhost:3000/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

问题根源

  • 同时配置了Spring Security的CORS和WebMvc的CORS,两者规则冲突,导致Security的CORS配置未生效
  • SecurityFilterChain中未显式启用CORS,Spring Security不会自动应用你定义的CorsConfigurationSource

解决方案

1. 移除WebMvc的CORS配置

删掉主应用类中的corsConfigurer() Bean,Spring Security的CORS处理优先级更高,共存会导致规则混乱。

2. 在SecurityFilterChain中启用CORS

在http配置链中添加CORS配置引用,让Spring Security使用你定义的规则。

3. 完善CorsConfiguration配置

补充请求头、凭证支持、预检缓存时间等配置,覆盖所有CORS场景。

修改后的完整代码

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                // 启用CORS并绑定配置源
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .authorizeHttpRequests(authorize ->
                        authorize
                                .requestMatchers("/api/v1/auth/register", "/api/v1/auth/login")
                                .permitAll()
                                .anyRequest()
                                .authenticated()
                )
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource(){
        CorsConfiguration configuration = new CorsConfiguration();
        // 指定允许的源,若需携带凭证(如Cookie),不能用*
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        // 显式允许OPTIONS方法(预检请求专用)
        configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "OPTIONS"));
        // 允许所有请求头
        configuration.setAllowedHeaders(Arrays.asList("*"));
        // 允许携带凭证(根据前端需求开启)
        configuration.setAllowCredentials(true);
        // 预检请求缓存时间,减少重复OPTIONS请求
        configuration.setMaxAge(3600L);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

关键说明

  • 添加.cors()配置后,Spring Security会自动拦截并处理OPTIONS预检请求,返回正确的CORS响应头
  • 显式允许OPTIONS方法是解决预检请求失败的核心
  • 若前端需要发送认证信息(如JWT、Cookie),必须开启setAllowCredentials(true),同时allowedOrigins不能使用通配符*

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:40:34