Apply [Authorize] attribute implicitly to all Web API controllers

amcdnl picture amcdnl · Feb 20, 2014 · Viewed 24.8k times · Source

My application is setup where all requests except login must be 'authorized' using the authorization attribute in Web API. E.g.

 [Authorize]
 [HttpGet, Route("api/account/profile")]
 public ApplicationUser Profile()
 {
       return userModel;
 }

and only the login needs to not authorize since thats where you get the token ;)

[AllowAnonymous]
[HttpPost, Route("api/account/login")]
public async Task<IHttpActionResult> Login(LoginViewModel model)
{
   ....
}

instead of having to add the [Authorize] attribute to ALL my routes, is there a way to set it globally?

Answer

ssilas777 picture ssilas777 · Feb 20, 2014

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