**不需額外資料表**,利用密碼學簽章確保 Token 不可偽造、不可重放、可驗證過期。
Token = Base64UrlEncode( userId | timestamp | HMAC_SHA256(userId + "|" + timestamp, SecretKey) )
const string SecretKey = "超長隨機密鑰僅存伺服器環境變數";
void SendResetEmail(string email) {
var user = Db.GetUserByEmail(email);
if (user == null) return; // 為防枚舉,仍回傳「若信箱存在會寄送郵件」
long ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
string payload = $"{user.Id}|{ts}";
string hmac = ComputeHmacSha256(payload, SecretKey);
string token = Base64UrlEncode(payload + "|" + hmac);
string link = $"https://domain.com/reset-password?token={token}";
EmailService.Send(email, "密碼重設", $"請於 1 小時內點擊:{link}");
}
bool ValidateToken(string token, out long userId, out long timestamp) {
userId = 0; timestamp = 0;
try {
string decoded = Base64UrlDecode(token);
var parts = decoded.Split('|');
if (parts.Length != 3) return false;
userId = long.Parse(parts[0]);
timestamp = long.Parse(parts[1]);
string expectedHmac = ComputeHmacSha256($"{parts[0]}|{parts[1]}", SecretKey);
if (!SlowEquals(parts[2], expectedHmac)) return false; // 恆時比較防時序攻擊
if (DateTimeOffset.UtcNow.ToUnixTimeSeconds() - timestamp > 3600) // 1 小時
return false;
return true;
} catch { return false; }
}
// 重設頁面 POST
void ResetPassword(string token, string newPassword, string confirmPassword) {
if (newPassword != confirmPassword) { ShowError("兩次輸入不一致"); return; }
if (!ValidateToken(token, out var userId, out _)) { ShowError("連結無效或已過期"); return; }
// 強制密碼策略
if (!PasswordPolicy.IsValid(newPassword)) { ShowError("密碼強度不足"); return; }
// 使用強雜湊 (Argon2id / bcrypt / PBKDF2)
string hash = PasswordHasher.Hash(newPassword);
Db.UpdatePasswordHash(userId, hash);
// 可選:撤銷所有現有 Session/Refresh Token
SessionStore.RevokeAll(userId);
ShowSuccess("密碼已更新,請重新登入");
}
| 風險 | 對策 |
|---|---|
| Token 洩漏 (郵件轉發、Referer、日誌) | 短效期 (≤1hr)、一次性 (驗證後標記失效或刪除)、HTTPS 全站 |
| 使用者枚舉 (測試 Email 是否存在) | 前端/後端統一回傳「若信箱存在會寄送郵件」,不洩露存在性 |
| 弱密碼 | 前端即時強度提示、後端強制策略 (長度、字元類別、禁用常見密碼) |
| 重放攻擊 | Token 包含 timestamp,驗證後可選「標記已用」或直接依靠時效過期 |
| 時序攻擊比對 HMAC | 使用恆時比較 `SlowEquals` (如 `FixedTimeEquals`) |
| CSRF | 重設頁面表單加入 CSRF Token (雖然 Token 本身具備單次性) |
若系統已使用 JWT,可直接簽發短效 `password_reset` scope 的 JWT,載荷含 `sub` (userId)、`exp`、`jti` (防重放),驗證邏輯統一由 JWT 中介軟體處理。
安全的密碼重設核心在於:**無狀態簽章 Token + 短效期 + 強雜湊儲存 + 防枚舉 + 全程 HTTPS**。避免自行設計加密演算法,善用成熟庫 (ASP.NET Core DataProtection、Java JJWT、Python itsdangerous) 即可構建符合 OWASP 建議的重設流程。