如何安全存储和使用jwt token
1. 优先使用 HTTP-Only Secure Cookie
优点:
- 浏览器自动处理 Cookie,避免前端直接访问,防止 XSS 攻击。
- 可通过
SameSite
限制跨站请求。
操作:
- 前端 API 请求:
使用浏览器自动附带的 Cookie,而无需手动管理:
fetch('/api/preferences', {
method: 'GET',
credentials: 'include', // 允许发送 Cookie
}).then(response => response.json())
.then(data => console.log(data));
服务器存储 Token 时设置 HttpOnly
, Secure
, 和 SameSite
属性:
Set-Cookie: token=your-token-here; HttpOnly; Secure; SameSite=Strict
2. 使用 Local Storage + Short-lived Access Token
原理:
- 将 Access Token 存储在
localStorage
。 - 短时间有效性,过期后使用 Refresh Token 或重新登录。
优点:
- 实现简单,Token 直接获取,适合前端场景。
- 减少长期凭据泄露风险。
实现:
- 缺点及解决:
localStorage
不安全,容易被 XSS 攻击利用:- 可以启用 CSP(Content Security Policy)限制脚本来源。
- 定期轮转 Token。
每次 API 请求在 Header 带上 Token:
const token = localStorage.getItem('token');
fetch('/api/preferences', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
},
}).then(response => response.json())
.then(data => console.log(data));
Token 保存到 localStorage
:
localStorage.setItem('token', yourToken);
3. 使用 Session Storage
(临时 Token 保存)
- 与
localStorage
类似,但浏览器会话结束时自动清除数据。 - 适合用户短期登录的情况。
4. Token 的轮转机制
无论选择哪种方法,都建议使用轮转机制提升安全性:
- Access Token 短时间有效(如 15 分钟):
- 过期后通过 Refresh Token 获取新 Access Token。
- 确保 Refresh Token 保存在
HttpOnly Secure Cookie
中。
- 后端刷新 API:
提供一个 /refresh-token
接口,用于定期发放新 Token:
fetch('/refresh-token', {
method: 'POST',
credentials: 'include'
})
.then(response => response.json())
.then(({ token }) => {
localStorage.setItem('token', token);
});
5. 结合场景做权衡
- 如果安全性要求高(如涉及敏感数据):优先使用 Cookie。
- 如果用户体验优先:采用
localStorage
或sessionStorage
+ 安全机制。
总结:
- 理想方案:
Access Token
存在内存中或短期内有效,使用HttpOnly Secure Cookie
保存Refresh Token
,后端通过接口刷新令牌。 - 避免在全局环境中长时间暴露
Access Token
或存储敏感数据。