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

Spring REST使用withCredentials: true时遇CORS错误,如何解决?

解决方案

问题核心:当请求携带withCredentials: true时,CORS响应头Access-Control-Allow-Origin不能使用通配符*,必须明确指定前端源地址,同时需开启凭证传递权限。

修改后端@CrossOrigin注解配置

将原空注解替换为指定源地址并允许凭证的配置:

@RestController
@RequestMapping("/api/auth")
// 指定前端源地址,同时开启凭证允许
@CrossOrigin(origins = "http://localhost:8080", allowCredentials = "true")
public class AuthController {
    // ... 原有代码保持不变
}

若需支持多个前端源,可使用数组形式:

@CrossOrigin(origins = {"http://localhost:8080", "https://your-frontend-domain.com"}, allowCredentials = "true")

生产环境优化建议

避免硬编码源地址,可将允许的源配置到application.properties(或application.yml)中:

application.properties

cors.allowed-origins=http://localhost:8080,https://your-production-domain.com

修改Controller注解

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "${cors.allowed-origins}", allowCredentials = "true")
public class AuthController {
    // ... 原有代码保持不变
}

此方式可通过配置文件灵活调整允许的前端源,无需修改代码。

验证要点

  1. 后端响应头需包含Access-Control-Allow-Origin: http://localhost:8080(而非*)
  2. 后端响应头需包含Access-Control-Allow-Credentials: true
  3. 前端已正确设置withCredentials: true(你的代码已满足此要求)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:07:53