Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply [Authorize] attribute implicitly to all Web API controllers

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?

like image 249
amcdnl Avatar asked Feb 20 '14 18:02

amcdnl


People also ask

Where can the Authorize attribute can be applied?

You can place the Authorize attribute on a controller or on individual actions inside the controller. When we place the Authorize attribute on the controller itself, the authorize attribute applies to all of the actions inside.

What happens if you apply the AllowAnonymous attribute to a controller action that already uses the Authorize attribute?

If you combine [AllowAnonymous] and any [Authorize] attribute, the [Authorize] attributes are ignored. For example if you apply [AllowAnonymous] at the controller level, any [Authorize] attributes on the same controller (or on any action within it) is ignored.

Which method is used to implement Authorize attribute?

In ASP.NET Web API authorization is implemented by using the Authorization filters which will be executed before the controller action method executed. Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated.


2 Answers

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()); 
like image 196
ssilas777 Avatar answered Sep 22 '22 22:09

ssilas777


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.

like image 31
Lin Avatar answered Sep 23 '22 22:09

Lin