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

ASP.NET MVC 驗證與授權實作:基於 ActionFilter 的角色權限控制方案

     編輯:關於ASP.NET

ASP.NET MVC (CTP3/RC 時期) 尚無官方授權框架。本文探討如何復用 ASP.NET Forms 驗證機制,透過自訂 ActionFilterAttribute 實現基於角色的 Controller/Action 級權限控制,並比較繼承 BaseController 重寫虛擬方法的替代方案。

核心挑戰

  • MVC 無實體 .aspx 檔案,web.config `` 路徑授權失效。
  • 請求入口是 Controller Action,需在 Action 執行前攔截驗證。

攔截機制:IActionFilter 與 ActionFilterAttribute

public interface IActionFilter
{
    void OnActionExecuting(ActionExecutingContext filterContext);
    void OnActionExecuted(ActionExecutedContext filterContext);
    void OnResultExecuting(ResultExecutingContext filterContext);
    void OnResultExecuted(ResultExecutedContext filterContext);
}

public abstract class ActionFilterAttribute : Attribute, IActionFilter { ... }

兩種套用方式:

  1. 屬性標記:`[RequiresAuthentication]`、`[RequiresRole("Admin\")]` 套用於 Class/Method。
  2. 基底類別重寫:Controller 實作 IActionFilter,重寫四個虛擬方法,效能略優但擴充性差。

社群成熟方案:兩個核心 Attribute

1. RequiresAuthenticationAttribute (強制登入)

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            var redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
            var redirectUrl = $"?ReturnUrl={redirectOnSuccess}";
            var loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
            filterContext.HttpContext.Response.Redirect(loginUrl, true);
        }
    }
}

2. RequiresRoleAttribute (角色授權)

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class RequiresRoleAttribute : ActionFilterAttribute
{
    public string RoleToCheckFor { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (string.IsNullOrEmpty(RoleToCheckFor))
            throw new InvalidOperationException("No Role Specified");

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            var redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
            var loginUrl = FormsAuthentication.LoginUrl + $"?ReturnUrl={redirectOnSuccess}";
            filterContext.HttpContext.Response.Redirect(loginUrl, true);
            return;
        }

        if (!filterContext.HttpContext.User.IsInRole(RoleToCheckFor))
            throw new UnauthorizedAccessException("You are not authorized to view this page");
    }
}

使用範例

[RequiresAuthentication]
public class AdminController : Controller
{
    [RequiresRole("SuperAdmin")]
    public ActionResult UserManagement() { ... }

    [RequiresRole("ContentEditor")]
    public ActionResult ArticleEdit(int id) { ... }
}

方案比較

展望:官方授權框架演進

  • MVC 1.0 RTM 引入 AuthorizeAttribute 內建支援角色/使用者授權。
  • MVC 3+ 整合 IAuthorizationFilter、FilterProviders、全域過濾器註冊。
  • ASP.NET Core 採用 Policy-based Authorization ([Authorize(Policy=\"AdminOnly\")]),支援需求/處理器模式,極度彈性。

總結

早期 MVC 透過自訂 ActionFilter 實現授權,展現框架擴充性。現代開發應直接使用內建 AuthorizeAttribute 或 Policy 授權,避免重造輪子,專注業務邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
維度ActionFilter AttributeBaseController 重寫
套用彈性類別/方法級,可多重疊加僅整個 Controller 統一策略
程式碼複用高,跨專案可攜低,需繼承特定基底
效能屬性反射略慢 (微乎其微)虛擬方法呼叫最快
測試友善易 Mock filterContext需建立 Controller 實例