Home » ASP » ASP.MVC » How to secure your Web Api Controller globally without having to use Authorize attribute

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

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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

3 Responses so far.

  1. Andrei Rinea says:

    Thank you so much! I had a tough time figuring this out.

  2. Tom says:

    Thank you!! I have been searching for hours trying to figure this out!

  3. Abhijeet says:

    Thank you, your post help me to figure out in less than a min. Came out as a third search result on google 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.