在行動裝置網頁開發中,提供「記住帳號密碼」功能能顯著提升使用者體驗。本文說明如何在 ASP.NET 應用程式中結合 Cookie 與前端技術實現此功能,並針對行動瀏覽器的特殊行為提供建議。
// 登入按鈕點擊事件
protected void btnLogin_Click(object sender, EventArgs e)
{
string username = txtUsername.Text.Trim();
string password = txtPassword.Text;
bool rememberMe = chkRememberMe.Checked;
// 驗證邏輯(略)
if (ValidateUser(username, password))
{
if (rememberMe)
{
// 建立加密 Ticket(實務上應使用 MachineKey 加密)
string userData = $"{username}|{Encrypt(password)}";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, username, DateTime.Now, DateTime.Now.AddYears(1), true, userData);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
HttpOnly = true,
Secure = Request.IsSecureConnection, // HTTPS 環境下啟用
Expires = DateTime.Now.AddYears(1)
};
Response.Cookies.Add(cookie);
}
else
{
// 清除記住我 Cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
{
Expires = DateTime.Now.AddDays(-1)
};
Response.Cookies.Add(cookie);
}
Response.Redirect("Default.aspx");
}
}
// 頁面載入時自動填入
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
try
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
string[] userData = ticket.UserData.Split('|');
txtUsername.Text = userData[0];
txtPassword.Text = Decrypt(userData[1]);
chkRememberMe.Checked = true;
}
catch { /* Cookie 損毀或解密失敗,忽略 */ }
}
}
}
若專案為 ASP.NET Core,建議直接使用內建的 SignInManager 與 RememberMe 參數,框架已處理加密、Cookie 選項等細節:
var result = await _signInManager.PasswordSignInAsync(
model.Username, model.Password, model.RememberMe, lockoutOnFailure: false);
正確實作「記住密碼」功能需在便利性與安全性間取得平衡,遵循最小權限原則、加密敏感資料、善用框架內建機制,才能提供既好用又安全的使用者體驗。