Custom Authorization with ASP.NET MVC
by
on July 28th, 2010 at 04:05 PM (1767 Views)
Lately, I've been doing a lot of work with the ASP.NET MVC framework. One of the greatest attributes of MVC over Web Forms is its extensibility. Authorization is important to any application and being able to customize it to meet your project's needs is equally important.
In the ASP.NET MVC framework, developers can use attributes to control things like validation and authorization. To have custom authorization in your MVC project, start off by inheriting from the AuthorizeAttribute class:
With this, you can put whatever logic you want to determine if a user should be authorized or not. All you have to do is return either True or False, depending on your own logic.Code:Public Class CustomAuthorizeAttribute Inherits AuthorizeAttribute Protected Overrides Function AuthorizeCore(ByVal httpContext As System.Web.HttpContextBase) As Boolean End Function End Class
The next thing you do is simply add the attribute to the controller method you wish to check authorization for:
From this example, you could have such code to authorize your users:Code:<CustomAuthorize> _ Public Function Index() As ActionResult Return View() End Function
Where the ModulePermissions enum is defined as:Code:Public Class CustomAuthorizeAttribute Inherits AuthorizeAttribute Public Permissions As ModulePermissions Protected Overrides Function AuthorizeCore(ByVal httpContext As HttpContextBase) As Boolean ' Ensure httpContext is not Nothing If httpContext Is Nothing Then ' Handle null value here End If ' Ensure the user is authenticated If Not httpContext.User.Identity.IsAuthenticated Then Return False End If ' Get user's permissions Dim permission As ModulePermissions = DirectCast([Enum].Parse(GetType(ModulePermissions), httpContext.Session("permissions")), ModulePermissions) ' Verify if user has perrmission If Permissions <> 0 AndAlso ((Permissions And permission) <> permission) Then Return False End If Return True End Function End Class
This can be used on your controller like so:Code:<Serializable()> _ <Flags()> _ Public Enum ModulePermissions CanViewDetails = 0 CanCreateNew = 1 CanEditOwn = 2 CanDeleteOwn = 3 End Enum
This will allow only users who have the CanViewDetails or CanCreateNew permissions. If they don't have one of these two permissions, they will be sent to the login page.Code:<CustomAuthorize(Permissions:=ModulePermissions.CanViewDetails Or ModulePermissions.CanCreateNew)> _ Function Index() As ActionResult Return View() End Function
Happy Coding!









Email Blog Entry