前端用localStorage存Refresh Token被恶意调用,怎么防?

淑怡酱~ 阅读 39

我在项目里用JWT方案,把Refresh Token存在localStorage里,但测试时发现如果前端页面被XSS攻击,Refresh Token会被直接窃取。虽然Access Token设置了短时效,但Refresh Token一旦泄露岂不是能无限刷新权限?

尝试过把Refresh Token改为HttpOnly cookie存储,但前端跨域请求时总提示credentials未正确配置。后端用Express时,即使设置了withCredentials=true,跨域预检还是返回401…

现在搞不清楚两种方案哪个更安全:是该坚持HttpOnly cookie方案,还是用加密存储Refresh Token在前端?有没有其他防护手段能防止Refresh Token被恶意使用?

// 前端请求示例
fetch('https://api.example.com/refresh-token', {
  method: 'POST',
  credentials: 'include',
  headers: { 'Content-Type': 'application/json' }
})
.then(res => {
  if (!res.ok) throw new Error('Refresh failed');
  return res.json();
})
.catch(err => console.error('Refresh error:', err));
我来解答 赞 4 收藏
二维码
手机扫码查看
2 条解答
Tr° 圆圆
localStorage确实不安全,XSS攻击下基本防不住。建议用HttpOnly Cookie存Refresh Token,配合CORS和CSRF防护。跨域问题是因为后端CORS配置不对,试试这个:

// 后端Express CORS配置
const cors = require('cors');
app.use(cors({
origin: 'https://your.frontend.domain',
credentials: true
}));

// 设置Refresh Token时的Cookie配置
res.cookie('refreshToken', token, {
httpOnly: true,
secure: true,
sameSite: 'none',
path: '/'
});


前端fetch保持credentials: 'include'就好,记得域名和协议要匹配。
点赞 7
2026-02-02 10:18
UE丶丹丹
直接这样:用HttpOnly + Secure的cookie存Refresh Token,前端完全别碰它。跨域问题是因为CORS配置没配对,后端要允许credentials,加这个:

app.use(cors({
origin: 'https://yourfrontenddomain.com',
credentials: true
}));


XSS防护单独搞,比如CSP头加上:script-src 'self'; 别想着靠加密存储来防,前端解密逻辑一样会被攻破。
点赞 9
2026-01-28 20:19