| 威脅 | 對策 |
| Cookie 竊取 (XSS/中間人) | HttpOnly + Secure + SameSite=Strict/Lax;Token 綁定 User-Agent/IP 指紋 |
| Token 暴力破解 | Token 長度 ≥ 128 bit (Base64 22字符);限制驗證頻率 |
| 數據庫洩露 | 存儲 Token 哈希 (bcrypt/Argon2) 而非明文 |
| 設備遺失 | 提供「吊銷所有 Token」功能;顯示活躍會話列表 |
最佳實踐代碼片段
// 登錄成功後
String token = UUID.randomUUID().toString().replace("-", "");
redisTemplate.opsForValue().set("auto_login:" + token, userId, 30, TimeUnit.DAYS);
Cookie cookie = new Cookie("remember_me", token);
cookie.setHttpOnly(true);
cookie.setSecure(true); // 僅 HTTPS
cookie.setPath("/");
cookie.setMaxAge(30 * 24 * 3600);
response.addCookie(cookie);
// 攔截器/過濾器中
String token = WebUtils.getCookie(request, "remember_me");
if (token != null) {
String userId = redisTemplate.opsForValue().get("auto_login:" + token);
if (userId != null) {
// 自動登錄
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userId, null, authorities));
}
}
結論
採用獨立長效 Token + HttpOnly Cookie + 服務端存儲架構,而非依賴 JSESSIONID。簡單、安全、符合標準。
- 上一篇文章: CPU 地址寬度與內存容量:32位/64位架構下的尋址邊界
- 下一篇文章: TreeView 采購單展示第三季:空產品號處理方案
Copyright ©
程式碼之家 All Rights Reserved