Spring Boot+React使用JWT认证时Authorization头的CORS配置错误
解决React + Spring Boot JWT认证的CORS跨域问题
问题核心原因
你的CORS配置里allowedOrigins末尾多了斜杠,Spring对源的匹配是严格字符串匹配,而浏览器发送的Origin是http://localhost:3000(无末尾斜杠),导致配置不生效,预检请求返回的响应没有Access-Control-Allow-Origin头,触发跨域拦截。同时你同时配置了两种CORS规则(WebMvcConfigurer和CorsConfigurationSource Bean),可能导致规则冲突,需要统一配置方式。
具体修复步骤
1. 修正CORS配置中的源地址
把所有allowedOrigins里的http://localhost:3000/改为http://localhost:3000(去掉末尾斜杠)。
2. 统一CORS配置方式(二选一即可)
方式一:使用WebMvcConfigurer(适合简单场景)
删除主应用中的corsConfigurationSource Bean,只保留CorsConfig类并修正配置:
@Configuration @EnableWebMvc public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry){ registry.addMapping("/api/v1/**") // 去掉末尾斜杠,匹配浏览器实际发送的Origin .allowedOrigins("http://localhost:3000") .allowedMethods("GET","POST","PUT","DELETE","OPTIONS") // 允许所有请求头,包含Authorization .allowedHeaders("*") .exposedHeaders("Authorization") .allowCredentials(true) .maxAge(3600); } }
方式二:使用CorsFilter(适合复杂场景)
删除CorsConfig类,在主应用中保留CorsConfigurationSource Bean并修正:
@Bean CorsConfigurationSource corsConfigurationSource() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 去掉末尾斜杠 config.addAllowedOrigin("http://localhost:3000"); config.addAllowedHeader("*"); config.addExposedHeader("Authorization"); config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("HEAD"); config.addAllowedMethod("GET"); config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("PATCH"); // 仅匹配API路径,避免全局规则冲突 source.registerCorsConfiguration("/api/v1/**", config); return source; }
3. 前端代码优化(非跨域问题,简化冗余逻辑)
Axios会自动解析JSON响应,无需手动调用res.json(),可简化代码:
const getCategory = () => { const token = localStorage.getItem("user"); return axios .get("http://localhost:8080/api/v1/category", { withCredentials: true, headers: { Authorization: `Bearer ${token}`, }, }) .then((res) => setCategory(res.data)) .catch(function (error) { console.log(error); }); };
验证要点
- 重启Spring后端服务,确保配置生效
- 打开浏览器开发者工具的网络面板,查看OPTIONS预检请求的响应头,确认包含
Access-Control-Allow-Origin: http://localhost:3000和Access-Control-Allow-Credentials: true
内容的提问来源于stack exchange,提问作者Nikos Chrysafis
相关产品推荐
相关产品推荐

