React JS中如何通过HttpOnly Cookie存储的Refresh Token刷新访问令牌
问题解决方案
无法获取Cookie的根因
HttpOnly 类型 Cookie 的核心设计规则就是禁止前端 JavaScript 通过任意 API 读取,目的是防范 XSS 攻击盗取敏感凭证,你调用document.cookie或cookie.get返回 undefined 是完全符合预期的正常行为,并非代码逻辑错误。
正确实现方式
你不需要手动获取 refresh token 并放到请求体中,调整前后端逻辑即可完成续期:
前端配置调整
给 axios 请求开启withCredentials: true配置,浏览器会自动将当前域名下的所有 HttpOnly Cookie(含 refresh token)附带在请求中发送给后端,不需要你手动取值传递:
axios.post('http://localhost:8000/api/token/refresh/', {}, // 无需再手动传入refresh参数 { withCredentials: true } // 开启跨域请求携带Cookie的开关 ).then(response => { // 拿到新的access token做后续处理 })
后端适配调整
- 调整 refresh 接口逻辑,不再从请求体中读取 refresh 参数,改为直接从请求的 Cookie 中读取 refresh token 做验签、续期操作
- 调整跨域响应头配置:
Access-Control-Allow-Credentials必须设为trueAccess-Control-Allow-Origin不能使用通配符*,必须指定为你前端的实际访问地址(比如http://localhost:3000)
额外说明
如果后端暂时无法调整接口逻辑,要求必须从请求体传 refresh 参数,那你只能修改服务端下发 Cookie 的逻辑,去掉 refresh token Cookie 的 HttpOnly 标记,但该操作会大幅降低凭证安全性,不推荐这么做。
内容的提问来源于stack exchange,提问作者Clark
相关产品推荐
相关产品推荐

