I have a default CustomAuthorizeAttribute
defined in my Web Api project.
config.Filters.Add(new CustomAuthorizeAttribute());
However I have a special Controller where I would like to use a SpecialAuthorizeAttribute
.
[SpecialAuthorize]
public class MySpecialController : ApiController
In the Asp.Net vNext we have a new attribute to override the default filters, but how could I make it work in the Web Api 2?
Edit 1:
One possible (but not ideal) solution is make the CustomAuthorizeAttribute check if there's another AuthorizeAttribute in the scope of the Controller or Action. In my case I have only the SpecialAuthorizeAttribute so:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<SpecialAuthorizeAttribute>().Any() || actionContext.ActionDescriptor.GetCustomAttributes<SpecialAuthorizeAttribute>().Any())
{
return;
}
base.OnAuthorization(actionContext);
}
public override System.Threading.Tasks.Task OnAuthorizationAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
{
return base.OnAuthorizationAsync(actionContext, cancellationToken);
}
}
You can use OverrideAuthenticationAttribute. As you can this answer this attribute is used to suppress global authentication filters.