Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to secure your Web Api Controller globally without having to use Authorize attribute

Posted on: 2013-05-05

If you are using Web Api of .Net 4.5 framework and want to have the same behavior of Asp.Net MVC which let you have global authorization set to every http request, than you need to configure your website differently.

In Asp.Net you would add a new filter to the FilterConfig file.

public static void RegisterGlobalFilters(GlobalFilterCollection filters) { 
  filters.Add(new HandleErrorAttribute()); 
  filters.Add(new AuthorizeAttribute()); 
} 

But, this won't work with the Api controller. You have to set the AuthorizeAttribute to the WebApiConfig file.

public static void Register(HttpConfiguration config) { 
  config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );

  config.Filters.Add(new AuthorizeAttribute()); 
} 

From here, every method of all your controllers will require authorization. If you want to remove this required authorization for specific web method, you need to add the attribute [AllowAnonymous]. You can have additional information directly at Microsoft.