身份驗證安全
規則
- 使用 bcrypt(成本因子 12 以上)或 argon2id 對密碼進行雜湊處理 — 絕不安放明文密碼或使用 SHA/MD5
- 對登入端點實施速率限制:每個 IP 每分鐘最多 5 次嘗試,每個帳號每小時最多 10 次
- 實施指數級鎖定:失敗後依序鎖定 1 秒、2 秒、4 秒、8 秒...,累計 10 次失敗後硬鎖 15 分鐘
- 密碼重置令牌:需為加密隨機生成、一次性使用,並在 1 小時內過期
- 回傳通用錯誤訊息:「電子郵件或密碼無效」 — 絕不洩露哪個欄位錯誤
- 強制密碼長度至少 8 個字元,並檢查是否出現在外洩密碼列表中(HaveIBeenPwned API)
import bcrypt from "bcrypt";
const hash = await bcrypt.hash(password, 12);
const valid = await bcrypt.compare(password, storedHash);
if (!valid) {
await incrementFailedAttempts(userId);
return res.status(401).json({ error: "Invalid email or password" });
}
await resetFailedAttempts(userId);
async function checkLockout(userId: string) {
const attempts = await getFailedAttempts(userId);
if (attempts.count >= 10) {
const lockoutEnd = attempts.lastAttempt + 15 * 60 * 1000;
if (Date.now() < lockoutEnd) throw new Error("帳戶暫時鎖定");
}
}
避免
- 將密碼以明文、base64 或可逆加密方式儲存
- 對密碼使用 SHA-256 — 因其速度快,易於暴力破解
- 在登入或密碼重置時洩露郵箱是否存在
- 使用永不失效或可重複使用的密碼重置連結
- 允許來自單一 IP 的無限登入嘗試