简体   繁体   中英

How override the global AuthorizeAttribute when add same AuthorizeAttribute for some Action MVC?

This is my CustomAuthorizeAttribute class:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{

       public string ControllerName { get; set; }


      public override void OnAuthorization(AuthorizationContext filterContext)
      {
           if (ControllerName != "pass")
           {
            // stop or redirect
           }

      }
}

I register it to global filters for all controller can use:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
      filters.Add(new AdminAuthorizeAttribute());
}

For some specific Action I add it with the param ControllerName :

[AdminAuthorize(ControllerName="pass")]
public ActionResult Index()
{
      return View();
}

But the problem is now in the OnAuthorization() , the ControllerName is always get null when execute the specific Action.

Is that because I can't use the global authorizeAttribute and same Attibute for some specific Action together ?? Why? I always thought if I add some AuthorizeAttribute for specific Action, and add the Attribute to global filter , the specific Action will get height priority .

Update1:

If the problem source is 2 authorized all execute. then How do I override the global authorized filter when I add a same AuthorizeAttribute for Some Action? (only different is the param, I just want it ignore the global authorized when I add one for some Action)

I did this with combination of Order property and marking in context items that the request has been authorized by on of my attributes:

public class AuthorizeByRolesAttribute : AuthorizeAttribute
{
    private const string AuthorizedContextItemName = "_AuthorizedByRoles";

    public AuthorizeByRolesAttribute (params string[] roles)
    {
        this.Order = 0;
        this.Roles = string.Join (",", roles);
    }

    public override void OnAuthorization (AuthorizationContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Items[AuthorizedContextItemName] != null)
            return;

        base.OnAuthorization (filterContext);

        filterContext.RequestContext.HttpContext.Items[AuthorizedContextItemName] = this.Roles ?? string.Empty;
    }
}

In global configs:

filters.Add (new AuthorizeByRolesAttribute ("Admin"), 255);

In controller simply:

[AuthorizeByRoles ("NotAdminButCanAccess")]
public class MyController : Controller
...

Change to Order property on the custom attribute, so that it will be fired first:

[AdminAuthorize(ControllerName="pass", Order=999)]
public ActionResult Index()
{
      return View();
}

this is an example offcourse.

And yes, you can override global filters this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM