萬盛學電腦網

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

ASP.NET Forms Authentication 表單驗證完整實作指南

前言

Forms Authentication 是 ASP.NET 經典的票據型驗證機制,透過加密 Cookie 儲存使用者身分,配合 `web.config` 授權規則自動保護資源。本文示範從設定、登入、角色授權到登出的完整流程。

1. Web.config 設定

<configuration>
  <system.web>
    <!-- 驗證模式 -->
    <authentication mode="Forms">
      <forms name=".MYAPPAUTH" 
             loginUrl="~/Account/Login.aspx" 
             defaultUrl="~/Default.aspx" 
             timeout="30" 
             slidingExpiration="true" 
             protection="All" 
             requireSSL="false" /> <!-- 正式環境改 true -->
    </authentication>

    <!-- 授權規則:保護 Admin 資料夾 -->
    <location path="Admin">
      <system.web>
        <authorization>
          <deny users="?" /> <!-- 拒絕匿名 -->
          <allow roles="Admin" /> <!-- 僅允許 Admin 角色 -->
        </authorization>
      </system.web>
    </location>
  </system.web>
</configuration>

關鍵屬性說明

  • `name`:Cookie 名稱,多應用程式部署同一網域時必須唯一。
  • `slidingExpiration="true"`:使用者活動時自動延長 Cookie 存活時間。
  • `protection="All"`:驗證 + 加密 (預設),防止竄改與偷窺。
  • `requireSSL="true"`:生產環境**必須**開啟,確保 Cookie 只在 HTTPS 傳輸。

2. 登入頁面 (Login.aspx)

<asp:TextBox ID="txtUser" runat="server" placeholder="帳號" />
<asp:TextBox ID="txtPwd" runat="server" TextMode="Password" placeholder="密碼" />
<asp:CheckBox ID="chkRemember" runat="server" Text="記住我" />
<asp:Button ID="btnLogin" runat="server" Text="登入" OnClick="btnLogin_Click" />
<asp:Label ID="lblMsg" runat="server" ForeColor="Red" />
protected void btnLogin_Click(object sender, EventArgs e)
{
    // 1. 驗證帳密 (此處示範,實務查資料庫、驗證雜湊)
    if (ValidateUser(txtUser.Text.Trim(), txtPwd.Text))
    {
        // 2. 建立驗證票並導向原請求頁 (或 defaultUrl)
        FormsAuthentication.RedirectFromLoginPage(txtUser.Text.Trim(), chkRemember.Checked);
    }
    else
    {
        lblMsg.Text = "帳號或密碼錯誤";
    }
}

private bool ValidateUser(string username, string password)
{
    // 實作:查資料庫、比對密碼雜湊 (參考文章 67518)
    return username == "admin" && password == "admin"; // 示範用
}

3. 判斷登入狀態與取得使用者資訊

// 任意頁面 / UserControl / MasterPage
if (User.Identity.IsAuthenticated)
{
    string username = User.Identity.Name; // 登入時傳入的 name
    // 顯示歡迎訊息、登出連結等
}
else
{
    // 顯示登入連結
}

4. 角色型授權 (Role-Based)

Global.asax 設定角色

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    if (Context.User != null && Context.User.Identity.IsAuthenticated)
    {
        // 從資料庫/快取取得角色
        string[] roles = GetRolesForUser(Context.User.Identity.Name); // 如 new[] { "Admin", "Editor" }
        Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
    }
}

頁面/程式碼檢查角色

// .aspx 標記
<asp:Panel ID="pnlAdmin" runat="server" Visible="<%# User.IsInRole("Admin") %>">...</asp:Panel>

// 後台
if (User.IsInRole("Admin")) { /* 管理員功能 */ }

5. 登出

protected void btnLogout_Click(object sender, EventArgs e)
{
    FormsAuthentication.SignOut(); // 清除 Cookie
    Session.Abandon(); // 清除 Session
    Response.Redirect(FormsAuthentication.LoginUrl); // 導回登入頁
}

安全性加強清單

  1. HTTPS 全站:`requireSSL="true"` + HSTS 標頭。
  2. 密碼雜湊:資料庫儲存 PBKDF2/bcrypt/Argon2 雜湊,**絕不存明文**。
  3. 防暴力破解**:登入失敗計數、帳號鎖定、驗證碼。
  4. Cookie 設定**:`HttpOnly` (預設)、`Secure`、`SameSite=Lax/Strict` (需 .NET 4.7.2+ 或自行加標頭)。
  5. 移至 ASP.NET Core Identity**:新專案請直接使用內建 Identity,功能更完整 (TwoFactor、外部登入、Token、PasswordHasher 等)。
copyright © 萬盛學電腦網 all rights reserved