ASP.net MVC - authorize the controller for one user / role, but all users in one action

I have a controller like this:

[Authorize(Users="Admin")] public class MyController : Controller { ... [AllowAnonymous] public AllUsersAction() { } } 

Except that I really want to allow AllUsersAction , only remote users can hit it, not just Admin.

What to do?

EDIT: I know that I can enable the entire controller and provide more restrictions for all actions that should be available only to Admin . But I would prefer not to add attributes for every action except one.

The question can be better formulated: what would the implementation look like, what would allow this โ€œminimalismโ€, if this is currently impossible?

+6
source share
1 answer

Use the Authorize attribute without parameters for the controller:

 [Authorize] public class MyController : Controller { ... public AllUsersAction() { } [Authorize(Users="Admin")] public ActionResult OnlyForAdmin() { } } 

And specify Authorize attribute properties for roles / users for limited actions.

Unfortunately, the Authorize attribute on the controller bypasses authorization only if the action has the AllowAnonymous attribute. Fortunately, you can override the OnAuthorization method of the Authorize attribute to skip the authorization check in the controller. Authorize an attribute if the 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() { } } 
+10
source

Source: https://habr.com/ru/post/986751/


All Articles