首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET Cookie 讀寫與加密的實務範例(記住登入)

     編輯:ASP.NET 基礎

情境

登入頁提供「記住我」功能:勾選後將帳號、密碼加密寫入 Cookie,下次造訪自動填入;未勾選則清除 Cookie。

關鍵類別:UIHelper(加解密)

public static class UIHelper
{
    // 簡易 AES 加密示範,實務請用 DataProtectionProvider 或 ASP.NET Core Data Protection
    private static readonly byte[] Key = Encoding.UTF8.GetBytes("Your32CharLongSecretKey1234567890!!");
    private static readonly byte[] IV = Encoding.UTF8.GetBytes("16CharInitVector");

    public static string Encrypt(string plain)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Key; aes.IV = IV;
            var encryptor = aes.CreateEncryptor();
            byte[] plainBytes = Encoding.UTF8.GetBytes(plain);
            byte[] cipher = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
            return Convert.ToBase64String(cipher);
        }
    }

    public static string Decrypt(string cipher)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Key; aes.IV = IV;
            var decryptor = aes.CreateDecryptor();
            byte[] cipherBytes = Convert.FromBase64String(cipher);
            byte[] plain = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
            return Encoding.UTF8.GetString(plain);
        }
    }
}

登入頁後台完整邏輯

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var cookie = Request.Cookies["loginInfo"];
        if (cookie != null)
        {
            cbRemember.Checked = true;
            txtUser.Text = UIHelper.Decrypt(cookie["loginName"]);
            txtPwd.Attributes["value"] = UIHelper.Decrypt(cookie["pwd"]); // 顯示在 value 中
        }
        else
        {
            txtPwd.Attributes["value"] = "******";
        }
    }
}

protected void btnLogin_Click(object sender, EventArgs e)
{
    // 驗證碼、帳號狀態檢查略...

    if (UserService.Login(txtUser.Text.Trim(), SecurityHelper.HashPwd(txtPwd.Text.Trim())))
    {
        var cookie = Request.Cookies["loginInfo"];
        if (cbRemember.Checked)
        {
            if (cookie == null) cookie = new HttpCookie("loginInfo");
            SetCookie(cookie, 7); // 7 天有效
        }
        else
        {
            ExpireCookie(cookie); // 立即過期
        }
        Response.Redirect("/");
    }
    else
    {
        ShowAlert("帳號或密碼錯誤");
    }
}

private void SetCookie(HttpCookie cookie, int days)
{
    cookie.Values["loginName"] = UIHelper.Encrypt(txtUser.Text.Trim());
    cookie.Values["pwd"] = UIHelper.Encrypt(txtPwd.Text.Trim());
    cookie.Expires = DateTime.Now.AddDays(days);
    Response.AppendCookie(cookie);
}

private void ExpireCookie(HttpCookie cookie)
{
    if (cookie != null)
    {
        cookie.Expires = DateTime.Now.AddDays(-1);
        Response.AppendCookie(cookie);
    }
}

安全性重點

  1. 必須加密:Cookie 存放於客戶端,明文密碼極度危險。
  2. HttpOnly & Secure:生產環境請設定 `cookie.HttpOnly = true; cookie.Secure = true;`(需 HTTPS)。
  3. 不要直接存密碼:最佳實務是存「加密後的 Token」或「Refresh Token」,而非帳密;此範例僅供教學示範。
  4. SameSite:.NET 4.7.2+ 可設 `cookie.SameSite = SameSiteMode.Lax;` 防禦 CSRF。

常見錯誤提醒

  • 用 `Request.Cookies` 讀取、用 `Response.Cookies` 寫入/修改——兩者物件不同,切勿混淆。
  • 修改 Cookie 後必須 `Response.AppendCookie` 才會送回瀏覽器。
  • 設定 `Expires = DateTime.Now.AddDays(-1)` 即為刪除 Cookie,單純移除 `Values` 不會生效。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved