Creating Your Own ASP.NET MVC Authorization Attribute
Applying role-based security is easy in ASP.NET MVC: Just decorate the relevant action method/controller class with the Authorization attribute, specify the allowed roles, and you're done. Every once in a while, though, I have a case where role-based security isn't enough.
For example, a client needed security to be applied differently depending on whether the current user was in the eastern or western division of the company. We could've duplicated all the roles in the company (EasternManager vs. WesternManager) or tried to find some clever way to combine roles (for example, assign users to an Eastern or Western role in addition to assigning them to the Manager role) and stack authorization attributes on each method. In the end I decided it was just as easy to create my own division-based Authorization attribute.
To create your own Authorization attribute you just need to create a class that inherits from AuthorizeAttribute and override its AuthorizeCore method. Your AuthorizeCore method must return True or False depending on whether you decide the user is accepted or rejected. This example rejects everyone:
Public Class DivisionAuthorization
Protected Overrides Function AuthorizeCore(httpContext As HttpContextBase) As Boolean
If you want to send the user to a custom page of your own (rather than sending the Web server's default 404 page) you can also override the HandleUnauthorizeRequest method and use a redirect method inside the method to specify the controller/action method name that displays your rejection page.
One hint and one caveat before I'm done:
The hint: You can get ASP.NET MVC's opinion on whether the current user is authorized by calling the base AuthorizeCore method, and passing the same parameter that's passed to your AuthorizeCore method.
The caveat: Your AuthorizeCore method must be thread-safe, so you should only use local variables inside of it.
Posted by Peter Vogel on 09/24/2015