Search code examples
asp.net-mvcauthorizationauthorize-attribute

How does custom MVC Authorization work?


I'm having a bit of an issue understanding how Authorization works in MVC when we extend the Authorize attribute.

So in the code we have extended the AuthorizeAttribute like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AuthExtendAttribute : AuthorizeAttribute

We then add the extension to the list of global filters like this:

filters.Add(new AuthExtendAttribute());

Then the action methods are decorated with the Authorize attribute like this:

[Authorize]
public bool DoStuff()

My question is, will this new extension replace the default behavior of the [Authorize] attribute or will the framework still use the default behavior and then call the overridden methods in AuthExtendAttribute?

Also, why would I need to add the extension to the global filter list if I could simply decorate my action methods with [AuthExtend]?

Is it also true that with newer MVC applications we shouldn't be extending the Authorize attribute but rather we should be using the new Policy based authorization?


Solution

  • What you have are 2 separate action filters. By registering your new filter as a global filter, you're simply making it available to all actions in your app.

    With your original set-up, both filters will execute. If you want to control the order in which they get executed you can have a look at the Order and Scope properties; more info here: In what order are filters executed in asp.net mvc

    Also, why would I need to add the extension to the global filter list if I could simply decorate my action methods with [AuthExtend]?

    It depends on what you want to do. Your global filter will execute for all actions. Usually, you would only be using your extended attribute, I don't see why you'd use both. Not sure how your custom filter is implemented and how your authentication is set up but with the filter globally registered how will users log in (since they need to be authorized to access the sign in page)?

    I think it would be best if you just use your custom filter and add it on top of controllers and/or action as needed.

    Is it also true that with newer MVC applications we shouldn't be extending the Authorize attribute but rather we should be using the new Policy based authorization?

    I don't think that policy-Based Authorization and creating custom action filters are mutually exclusive.