Override authorization filter with another

3.3k views Asked by At

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

There are 2 answers

0
Pedro Drewanz On

You can use OverrideAuthenticationAttribute. As you can this answer this attribute is used to suppress global authentication filters.

0
Deepak Ageeru On

OverrideAuthorization attribute is the exact fit (in ASP.NET Web API 2) for your requirement. You can find its usage and purpose in simple terms in this article.