Spring Boot中Session Cookie未在浏览器存储问题排查与解决
Spring Boot登录会话异常:前端Fetch请求未存储Session导致重定向问题
问题场景
- 基于Spring Boot开发登录功能,核心依赖为
spring-boot-starter-security、spring-session-jdbc - 后端已在
SecurityConfig中配置CORS规则、会话管理策略 - Postman测试登录接口正常,后端响应返回Session,但前端使用React的Fetch API请求时:
- 浏览器未存储Session Cookie
- 后续访问认证接口时被重定向到登录页
根因排查
问题源于Fetch API的credentials配置位置错误:将credentials属性放在了headers对象内部,导致Fetch无法识别该配置,浏览器不会处理后端返回的Session Cookie。
解决方法
将credentials配置从headers移至Fetch请求配置的外层:
错误示例(导致问题的代码)
fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json', credentials: 'include' // ❌ 错误:credentials不应放在headers中 }, body: JSON.stringify({ username: 'xxx', password: 'xxx' }) })
正确示例(修复后的代码)
fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', // ✅ 正确:放在请求配置外层 body: JSON.stringify({ username: 'xxx', password: 'xxx' }) })
补充说明
credentials: 'include'的作用是告知浏览器在跨域请求中携带并存储Cookie(包括Session Cookie)。如果配置位置错误,浏览器会忽略后端返回的Session Cookie,导致后续请求因无有效会话凭证被Spring Security拦截并重定向到登录页。
内容的提问来源于stack exchange,提问作者Brettaten
相关产品推荐
相关产品推荐

