Is it possible to deny authorization (even for authenticated users) for every ASP.NET Web API controller in a project unless the authorization is explicitly allowed?
I am looking for something like:
WebApiConfig
config.Filters.Add(new DenyAuthorizationAttribute()); // ??
ExampleController.cs
public class ExampleController : ApiController
{
[Authorize(Roles = "Admins")]
public string GetHello_OnlyAdmins()
{
// only admins can call this
}
[AllowAnonymous]
public void PostSomething_Everybody()
{
// ...
}
public void DeleteSomething_NoOne()
{
// nobody can call this - we want to force the programmer to be specific about authorized roles
}
}
I have solved this by adding a custum "default deny" authorization filter to HttpConfiguration.Filters
:
public class DefaultDenyAuthorizationFilter : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if ( null == actionContext )
throw new ArgumentNullException("actionContext");
if ( actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any() ||
actionContext.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>().Any() ||
actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any() ||
actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AuthorizeAttribute>().Any() )
return;
base.HandleUnauthorizedRequest(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