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?
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.
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.
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.
You have two options
Controller level by decorating your controller with authorize attribute.
[Authorize] [RoutePrefix("api/account")] public class AccountController : ApiController {
You can also set it global level to all routes, in Register
method of WebApiConfig.cs file
config.Filters.Add(new AuthorizeAttribute());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With