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.
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);
}
}
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