Forms Authentication 是 ASP.NET 經典的票據型驗證機制,透過加密 Cookie 儲存使用者身分,配合 `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>
<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"; // 示範用
}
// 任意頁面 / UserControl / MasterPage
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name; // 登入時傳入的 name
// 顯示歡迎訊息、登出連結等
}
else
{
// 顯示登入連結
}
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")) { /* 管理員功能 */ }
protected void btnLogout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut(); // 清除 Cookie
Session.Abandon(); // 清除 Session
Response.Redirect(FormsAuthentication.LoginUrl); // 導回登入頁
}