許多開發者習慣在 HttpModule 中讀取 Session 驗證身分,卻不知 ASP.NET 內建的表單驗證(FormsAuthentication)配合自訂 IPrincipal/IIdentity 即可完成更安全、更標準的驗證授權流程,且無需綁定 ASPNetDB.mdf 或 Membership/Profile/Role 提供者。
public class CustomIdentity : IIdentity
{
public string Name { get; private set; }
public string Email { get; private set; }
public int UserId { get; private set; }
public string AuthenticationType => "Custom";
public bool IsAuthenticated => !string.IsNullOrEmpty(Name);
// 建構子略
}
public class CustomPrincipal : IPrincipal
{
public IIdentity Identity { get; private set; }
public string[] Roles { get; private set; }
public bool IsInRole(string role) => Roles?.Contains(role) ?? false;
// 建構子略
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (Context.User != null && Context.User.Identity.IsAuthenticated)
{
// 從 Ticket 或快取取得使用者資料
var identity = new CustomIdentity(...);
var principal = new CustomPrincipal(identity, roles);
Context.User = Thread.CurrentPrincipal = principal;
}
}
之後在頁面即可用 User.Identity.Name、((CustomIdentity)User.Identity).Email、User.IsInRole("Admin") 取得豐富資訊,並配合 <authorization>、PrincipalPermission 屬性實現聲明式授權。