Reputation: 4484
I have a MVC Web Api Controller that uses the [Authorize] attribute at the class level. This makes all of the api methods require authorization but I'd like to create an attribute called [ApiPublic] that overrides the [Authorize] attribute. There is a similar technique described here for normal MVC controllers.
I tried creating an AuthorizeAttribute based of the System.Web.Http.AuthorizeAttribute but none of the overridden events are called if I put it on a api method that has the [Authorize] at the class level. Anyone have an idea how to override the authorize for the web api?
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ApiPublicAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.HandleUnauthorizedRequest(actionContext);
}
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
}
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
return true;
}
}
Upvotes: 1
Views: 3449
Reputation: 3326
Can I recommend that you just use [AllowAnonymous] instead?
You can attribute this on any method and it will override the Authorize attribute you've specified at the class level, saving you from writing your own attribute.
Upvotes: 10