Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorize Attribute Lifecycle

Can someone explain why the authorize attribute lifecycle appears to be managed relative to the class or method it is applied to? This is as opposed to be managed relative to the request lifecycle.

If I decorate a controller at the class level the authorize attributes constructor only gets called once across multiple requests to the same controller. If I decorate each controller method then I get new authorize attribute constructor calls for each controller method called.

What's this behavior all about? I would expect the authorize attribute creation to happen every request.

like image 807
Daniel Avatar asked Sep 27 '13 17:09

Daniel


People also ask

How does the Authorize attribute work?

If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.

When should we use Authorize attribute?

This attribute is useful when you want to use the Authorize attribute on a controller to protect all of the actions inside, but then there is this single action or one or two actions that you want to unprotect and allow anonymous users to reach that specific action.

What is Authorize attribute in Web API?

Using the [Authorize] Attribute Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.


1 Answers

ASP.NET MVC will cache ActionFilters and try to reuse them on subsequent requests. The actual authorization will occur on each request but the contructor will only get called on the first. You should not maintain any internal state in an ActionFilter.

like image 69
Mark Olsen Avatar answered Nov 15 '22 20:11

Mark Olsen