Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Authorization role at Controller level and override at method

I'm trying to set default access to the methods on my controller, so I've added the [Authorize] attribute on my ApiController.

For the most part, unless overridden with the [AllowAnonymous] attribute this works fine.

Now I want to add another level into the mix. For my authorized methods by default, I want them to require a specific role (such as admin) so I updated the controller level attribute to [Authorize(roles="admin")]. For a few exceptions, I don't care what role they are (just being authenticated is good enough).

I thought I could stick with setting the Authorize attribute at the controller level and override it at the individual method level, but this doesn't appear to work the same way as [AllowAnonymous] does.

Are there any suggestions out there on how to go about this without having to remember to decorate every new method with the default access level? Something like [Authorize(roles="*")]? Even if I needed to have a default role that every user was a part of like AuthenticatedUsers, that would be fine.

like image 280
earthling Avatar asked May 07 '13 23:05

earthling


1 Answers

How about creating a marker attribute? AllowAnonymous is one such marker, BTW. Create your own Authorize attribute and clear the roles, when marker is there.

[MyAuth(Roles = "admin")]
public class ValuesController : ApiController
{
    [ExemptRoles]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

public class ExemptRolesAttribute : Attribute { }

public class MyAuthAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (actionContext.ActionDescriptor.GetCustomAttributes<ExemptRolesAttribute>().Any())
            base.Roles = String.Empty;

        base.OnAuthorization(actionContext);
    }
}
like image 130
Badri Avatar answered Oct 21 '22 13:10

Badri