5

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
    }

}
metalheart
  • 3,740
  • 1
  • 23
  • 29

2 Answers2

2

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);
    }
}
metalheart
  • 3,740
  • 1
  • 23
  • 29
1

Add this to your api configuration method in the globa.asax file:

    private static void ConfigureApis(HttpConfiguration config)
    {
        //create AuthorizeAttribute from System.Web.Http
        var auth = new AuthorizeAttribute { Roles = "Admin" };
        //add it to webapi configuration
        config.Filters.Add(auth);
    }
James
  • 2,195
  • 1
  • 19
  • 22