34

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?

Reinstate Monica Cellio
  • 24,939
  • 6
  • 47
  • 65
amcdnl
  • 7,766
  • 12
  • 59
  • 88

4 Answers4

62

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());
    
ssilas777
  • 9,166
  • 3
  • 41
  • 63
22

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.

Lin
  • 14,568
  • 4
  • 45
  • 49
2

In ASP.NET Core Web API, it's like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(o =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();

        o.Filters.Add(new AuthorizeFilter(policy));
    });
}

Source: https://joonasw.net/view/apply-authz-by-default

Matt Frear
  • 45,587
  • 10
  • 66
  • 82
1

I just wanted to add something to other answers that if you use

 filters.Add(container.Resolve<AuthorizeAttribute>());

then you can also inject all dependencies into your attribute if there is a need

samira riazati
  • 503
  • 7
  • 20