Reputation: 1377
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)
Upvotes: 3
Views: 2515
Reputation: 2569
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
...
Upvotes: 2
Reputation: 2333
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.
Upvotes: 1