Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deny authorization for a Web API project by default

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
    }

}
like image 418
metalheart Avatar asked Oct 20 '22 19:10

metalheart


1 Answers

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);
    }
}
like image 69
metalheart Avatar answered Oct 27 '22 14:10

metalheart