「記住我」功能讓使用者在瀏覽器關閉後下次造訪自動登入。核心做法是**登入成功時寫入持久性 Cookie (含加密票據),後續請求驗證 Cookie 並重建身分**。本文提供 ASP.NET Forms Authentication 整合版與自訂 Token 版兩種實作,並詳述安全性強化清單。
// 登入頁 Login.aspx.cs
protected void btnLogin_Click(object sender, EventArgs e) {
if (ValidateUser(txtUser.Text, txtPwd.Text)) {
// 建立驗證票據:第 3 參數 isPersistent = chkRememberMe.Checked
FormsAuthentication.SetAuthCookie(txtUser.Text, chkRememberMe.Checked);
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUser.Text, chkRememberMe.Checked));
} else {
lblError.Text = "帳號或密碼錯誤";
}
}
// web.config 設定票據加密與有效期
**機制**:`isPersistent=true` 時,Cookie `Expires` 設為 `timeout` 指定分鐘數後;`slidingExpiration=true` 表示每次請求延長有效期。
public class AuthService {
private static readonly TimeSpan PersistentExpiry = TimeSpan.FromDays(30);
private static readonly TimeSpan SessionExpiry = TimeSpan.FromMinutes(60);
public string IssueToken(string userId, bool persistent) {
var payload = new {
uid = userId,
iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
exp = DateTimeOffset.UtcNow.Add(persistent ? PersistentExpiry : SessionExpiry).ToUnixTimeSeconds(),
per = persistent
};
string json = JsonConvert.SerializeObject(payload);
return Protect(json); // MachineKey / DataProtection 加密
}
public (bool Valid, string UserId) ValidateToken(string token) {
try {
string json = Unprotect(token);
var payload = JsonConvert.DeserializeObject(json);
if (payload.Exp < DateTimeOffset.UtcNow.ToUnixTimeSeconds()) return (false, null);
return (true, payload.Uid);
} catch { return (false, null); }
}
// MachineKey 加密 (需 web.config 設定 validationKey/decryptionKey)
private string Protect(string plain) {
byte[] data = Encoding.UTF8.GetBytes(plain);
byte[] prot = MachineKey.Protect(data, "AuthToken");
return Convert.ToBase64String(prot);
}
private string Unprotect(string protectedText) {
byte[] data = Convert.FromBase64String(protectedText);
byte[] plain = MachineKey.Unprotect(data, "AuthToken");
return Encoding.UTF8.GetString(plain);
}
private class TokenPayload { public string Uid; public long Iat; public long Exp; public bool Per; }
}
protected void Application_AuthenticateRequest() {
var cookie = Request.Cookies["AuthToken"];
if (cookie == null) return;
var (valid, userId) = new AuthService().ValidateToken(cookie.Value);
if (valid) {
var identity = new GenericIdentity(userId);
var principal = new GenericPrincipal(identity, GetRoles(userId));
Context.User = Thread.CurrentPrincipal = principal;
}
}
// 前端登出
Response.Cookies["AuthToken"].Expires = DateTime.Now.AddDays(-1);
FormsAuthentication.SignOut(); // 若同時使用 FormsAuth
// 伺服端撤銷 (如修改密碼、封鎖帳號):需維護撤銷清單 (Redis Set) 或縮短 Token 有效期
// 簡易做法:Token 中含 lastPwdChange 時間,驗證時比對 DB 最新值
正確實作「記住我」需在**便利性**與**安全性**間取得平衡:預設關閉、明確用戶勾選才啟用、持久 Token 加密簽名並可撤銷、配合裝置指紋與異地登入警報,才能在保護帳號安全的前提下提供良好體驗。