I have a controller like this:
[Authorize(Users="Admin")]
public class MyController : Controller
{
...
[AllowAnonymous]
public AllUsersAction()
{
}
}
Except I actually do want to authorize AllUsersAction
, only all authorized users should be able to hit it, not just Admin.
What to do?
EDIT: I know that I can authorize the whole controller and provide more restrictions for all actions that should only be available to Admin
. But I'd rather not put attributes on every action but one.
The question could be better phrased: What would an implementation look like that would allow this 'minimalism' if it isn't currently possible?
Use Authorize attribute without any parameters for controller:
[Authorize]
public class MyController : Controller
{
...
public AllUsersAction()
{
}
[Authorize(Users="Admin")]
public ActionResult OnlyForAdmin()
{
}
}
And specify Authorize attribute Roles/Users properties for restricted actions.
Unfortunately Authorize attribute on controller bypasses authorization only if action has AllowAnonymous attribute. Fortunately you can override OnAuthorization method of Authorize attribute to skip authorization check in controller Authorize attribute if action has its own Authorize attribute:
public class CustomAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if(filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), true))
{
//skip authorization check if action has Authorize attribute
return;
}
base.OnAuthorization(filterContext);
}
}
You can use this CustomAuthorize in your example:
[CustomAuthorize(Users="Admin")]
public class MyController : Controller
{
...
[Authorize]
public AllUsersAction()
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With