How to secure your Web Api Controller globally without having to use Authorize attribute<!-- --> | <!-- -->Patrick Desjardins Blog
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: May 5, 2013

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.

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

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

1public static void Register(HttpConfiguration config) {
2 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
3
4 config.Filters.Add(new AuthorizeAttribute());
5}

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.