Asp.net-Mvc

為什麼 onAuthorization 在身份驗證之前執行?

  • June 20, 2016

我正在嘗試做一些自定義授權,所以我創建了一個覆蓋該OnAuthorization方法的控制器。我還將該Authorize屬性應用於此控制器。問題是為什麼OnAuthorization在基本表單身份驗證過程之前呼叫該方法?

我想在使用者通過身份驗證後對其進行授權。我錯過了什麼嗎?

這是程式碼:

[Authorize]
   public class AuthorizationController : Controller
   {
       protected override void OnAuthorization(AuthorizationContext filterContext)
       {
           base.OnAuthorization(filterContext);

           if (filterContext == null)
           {
               throw new ArgumentNullException("filterContext");
           }

           List<string> allowedControllers = new List<string>() { "SecurityController" };
           List<string> allowedActions = new List<string>() { "Index" };

           string controllerName = filterContext.Controller.GetType().Name;
           string actionName = filterContext.ActionDescriptor.ActionName;

           if (!allowedControllers.Contains(controllerName)
           || !allowedActions.Contains(actionName))
           {
               filterContext.Result = View("UnauthorizedAccess");
           }
       }
   }

我測試的控制器類似於:

public class SecurityController : AuthorizationController
{

   public ActionResult Index()
   {
       return View();
   }

   public ActionResult AnotherIndex()
   {
       return View();
   }
}

要做的第一件事AuthorizeAttribute就是檢查使用者是否經過身份驗證。如果不是,則將發出重定向到登錄頁面的時間。

基本上將AuthorizeAttribute身份驗證檢查與授權部分一起包裝:

protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
       if (httpContext == null) {
           throw new ArgumentNullException("httpContext");
       }

       IPrincipal user = httpContext.User;
       if (!user.Identity.IsAuthenticated) {
           return false;
       }

當您像在範例中那樣使用沒有角色/使用者的 AuthorizeAttribute 時(

$$ Authorize $$),它基本上只是檢查以確保在這種情況下使用者已通過身份驗證。 我可能會更改您的程式碼以覆蓋 AuthorizeAttribute 而不是在您的控制器中執行此程式碼。您可以執行以下操作:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
   public override void OnAuthorization(AuthorizationContext filterContext)
   {
       filterContext.Result = CreateResult(filterContext);
   }

   protected ActionResult CreateResult(AuthorizationContext filterContext)
   {
       var controllerContext = new ControllerContext(filterContext.RequestContext, filterContext.Controller);
       var controller = (string)filterContext.RouteData.Values["controller"];
       var action = (string)filterContext.RouteData.Values["action"];
       // any custom model here
       var model = new UnauthorizedModel(); 

       // custom logic to determine proper view here - i'm just hardcoding it
       var viewName = "~/Views/Shared/Unauthorized.cshtml"; 

       return new ViewResult
       {
           ViewName = viewName,
           ViewData = new ViewDataDictionary<UnauthorizedModel>(model)
       };
   }
}

引用自:https://stackoverflow.com/questions/9366085