Apply [Authorize] attribute implicitly to all Web API controllers

You can set the AuthorizeAttribute to the WebApiConfig file like below:

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());
}

Now all methods from your Web Api controllers will need authorization. If you want to remove this authorization requirement for a method, you need to add the attribute [AllowAnonymous] like in the Login action method.


You have two options

  1. Controller level by decorating your controller with authorize attribute.

    [Authorize]
    [RoutePrefix("api/account")]
    public class AccountController : ApiController
    {
    
  2. You can also set it global level to all routes, in Register method of WebApiConfig.cs file

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