萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 使用 Cookie 實現「記住我」自動登入:完整流程與安全強化

「記住我」功能讓使用者在瀏覽器關閉後下次造訪自動登入。核心做法是**登入成功時寫入持久性 Cookie (含加密票據),後續請求驗證 Cookie 並重建身分**。本文提供 ASP.NET Forms Authentication 整合版與自訂 Token 版兩種實作,並詳述安全性強化清單。

方案一:整合 FormsAuthentication (最簡單)

// 登入頁 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` 表示每次請求延長有效期。

方案二:自訂加密 Token (彈性高、可跨應用/微服務)

1. 登入發行 Token

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; }
}

2. 全域驗證 (Global.asax / HttpModule)

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;
    }
}

3. 登出/撤銷

// 前端登出
Response.Cookies["AuthToken"].Expires = DateTime.Now.AddDays(-1);
FormsAuthentication.SignOut(); // 若同時使用 FormsAuth

// 伺服端撤銷 (如修改密碼、封鎖帳號):需維護撤銷清單 (Redis Set) 或縮短 Token 有效期
// 簡易做法:Token 中含 lastPwdChange 時間,驗證時比對 DB 最新值

安全性強化清單 (必做)

  1. HttpOnly + Secure + SameSite=Lax/Strict:防 XSS 竊取、強制 HTTPS、防 CSRF。
  2. 簽名/加密:使用 `MachineKey` (WebForms) 或 `IDataProtector` (Core) 保護 Token 完整性與機密性。
  3. 旋轉金鑰:定期更換 `validationKey`/`decryptionKey`,舊 Token 自動失效。
  4. 綁定裝置指紋:Token 中加入 `fp` (User-Agent + IP 前綴 + Canvas 指紋),驗證時比對,異常則要求重新登入。
  5. 最小權限原則:Cookie `Path` 限制在需要驗證的應用程式路徑;`Domain` 僅設定根域名 (`.example.com`)。
  6. 記錄審計日誌:登入成功/失敗、Token 簽發/驗證/撤銷、IP、User-Agent 寫入不可變更存儲。

常見問題

  • 跨子域共享登入:設定 `Domain=".example.com"`,所有子域自動攜帶 Cookie。
  • Web Farm 多伺服器:`MachineKey` 必須所有節點**完全相同** (手動產生固定金鑰寫入 `web.config`),或改用 Redis Session / 分散式 Token 驗證。
  • 「記住我」不生效:檢查 `FormsAuthentication.SetAuthCookie` 第 2 參數確為 `true`、瀏覽器未封鎖第三方 Cookie、時間同步正確。

正確實作「記住我」需在**便利性**與**安全性**間取得平衡:預設關閉、明確用戶勾選才啟用、持久 Token 加密簽名並可撤銷、配合裝置指紋與異地登入警報,才能在保護帳號安全的前提下提供良好體驗。

copyright © 萬盛學電腦網 all rights reserved