React请求Spring Boot后端遇CORS错误:预检请求未通过凭证校验
问题
前端React(运行在http://localhost:5173)向Spring Boot后端(http://localhost:8080)发送认证请求时,遇到CORS错误:
Access to XMLHttpRequest at 'http://localhost:8080/auth/authenticate' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
当前后端CORS配置:
@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("http://localhost:5173"); } }; }
前端Axios请求代码:
await axios.post( "http://localhost:8080/auth/authenticate", { email: email, password: password, }, { headers: { "Content-Type": "application/json", }, withCredentials: true } );
已尝试:添加允许请求方法到CORS配置、改用Fetch API发送请求;移除withCredentials参数时请求正常,但需要获取后端通过httpOnly Set-Cookie头返回的JWT令牌。
解决方案
问题核心是后端CORS配置未显式允许凭据传递,而前端请求开启了withCredentials: true,这要求后端必须返回Access-Control-Allow-Credentials: true响应头。
修改Spring Boot的CORS配置,添加allowCredentials(true):
@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:5173") .allowCredentials(true) // 关键配置:允许凭据跨域传递 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS"); // 明确允许的请求方法,覆盖默认值 } }; }
额外注意事项
- 若项目集成Spring Security,需在Security配置中绑定CORS规则,例如:
@Override protected void configure(HttpSecurity http) throws Exception { http.cors().configurationSource(corsConfigurationSource()) // 其他Security配置... } - 后端设置
Set-Cookie时,建议添加SameSite=Lax(复杂跨域场景可设为SameSite=None并配合Secure属性),确保浏览器正常保存Cookie; - 当
allowCredentials设为true时,allowedOrigins不能使用通配符*,必须指定具体的源地址(当前配置已符合要求)。
内容的提问来源于stack exchange,提问作者wazzupek01
相关产品推荐
相关产品推荐

