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

Spring Boot整合Spring Security+React部署后CORS跨域访问失败问题问询

核心问题

你目前同时配置了3套CORS处理规则(Spring Security Cors配置、自定义Cors过滤器、WebMvc Cors配置),多套规则冲突会导致响应头重复或者规则不匹配,这是你后端返回数据正常但前端依然跨域的主要原因。

解决方案

1. 移除重复冗余的CORS配置

仅保留Spring Security原生的CORS配置即可,删除另外两套配置:

  • 删除自定义MyCorsFilter类,以及WebSecurity.java中对应的crosFilterRegistration Bean定义
  • 删除Application.java中的corsConfigurer Bean定义

2. 修正Spring Security的CORS配置

你当前corsConfigurationSource中的allowedHeaders配置错误,不需要包含Access-Control-*这类响应头字段,修改为业务实际需要的请求头即可,修正后的代码示例:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    // 这里替换为你的React应用实际访问域名,多个的话用list添加
    configuration.setAllowedOrigins(Collections.singletonList("https://你的React域名"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"));
    // 只保留实际需要的请求头
    configuration.setAllowedHeaders(Arrays.asList("Origin", "Cache-Control", "Content-Type", "Authorization"));
    configuration.setAllowCredentials(true);
    configuration.setMaxAge(3600L);

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

3. 检查前端fetch请求配置

如果你的请求携带认证信息(Cookie、JWT的Authorization头),需要在fetch请求中显式开启credentials配置:

fetch('你的API地址', {
  // 其他配置
  credentials: 'include'
})

4. 域名校验

确认setAllowedOrigins中配置的地址和React应用实际访问的地址完全一致,包含协议(http/https)、域名、端口,本地开发时需要额外添加http://localhost:3000这类本地地址。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:39:04