Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC - Authorize controller for one user/role but all users for one action

Tags:

asp.net-mvc

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?

like image 371
itslittlejohn Avatar asked May 07 '15 14:05

itslittlejohn


1 Answers

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()
    {

    }
}
like image 179
py3r3str Avatar answered Nov 01 '22 16:11

py3r3str