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.
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.
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.
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.
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.
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