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

ASP.NET 自訂 IPrincipal 與 IIdentity 實現使用者驗證:棄用 Cookie+Session,擁抱內建機制

     編輯:關於ASP.NET

許多開發者習慣在 HttpModule 中讀取 Session 驗證身分,卻不知 ASP.NET 內建的表單驗證(FormsAuthentication)配合自訂 IPrincipal/IIdentity 即可完成更安全、更標準的驗證授權流程,且無需綁定 ASPNetDB.mdf 或 Membership/Profile/Role 提供者。

核心觀念

  • 驗證:證明「你是誰」(如帳密比對)。
  • 授權:判斷「你能做什麼」(角色/權限)。

自訂 Identity 與 Principal

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;
    // 建構子略
}

在 Global.asax 綁定

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 屬性實現聲明式授權。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved