Click here to Skip to main content
Click here to Skip to main content

Extending ASP.NET role based Security with Custom Security Module (Permission Based, Page Level Authorization)

, 11 Nov 2011 Ms-PL
Rate this:
Please Sign up or sign in to vote.
This project intends to extend the default ASP.NET role based Security to include Permission Based / Page Level Authorization Layer. Works with both ASP.NET and ASP.NET MVC. Permission rules to Allow/Deny access to website resources (like "Folder/File.aspx" or "Controller/Action") are stored in DB.

Introduction

This project intends to extend the default ASP.NET role based Security to include Permission Based / Page Level Authorization. Permission rules to Allow/Deny access to website resources (like "Folder/File.aspx") will be stored in the database. Our "ADHPermissionsModule" validates each request on the basis of these Permission rules.

A basic ASP.NET MVC version of the same module (AadhaarMVC.zip) is included now (please pardon me for insufficient validations). The Custom Security Module's name (included inside the Controllers directory of MVC Project) is "ADHPermissionsModuleMVC" . I have tried to keep the versions of both the modules low to ensure better compatibility. Aadhaar.Data project uses .NET version 2.0. Nhibernate version 2.0 has been used for DB persistence layer. Aadhaar.MVC uses .NET v3.5 MVC.

Background

ASP.NET provides us a very good default Role Based security to control and authorize access to our website. As the security is provider based, we can rewrite our own membership and role providers and decide how we want to store the data.

Although in smaller web applications, we already know the structure of the website and the required Roles, hence access rules can be directly configured by modifying (manually or programmatically) the web.config to allow/restrict access to various resources/pages. (something like <allow users="user1,user2" /> <allow roles="superadmin">). One of the approaches I tried to cover in my previous attempt here to modify the web.config for different locations as normal XML.

But what if instead of modifying the web.configs of different location, we would like to store the permission rules into a database instead? (This would give us a bit more flexibility to create/remove/modify the Permission rules for a particular location {"Folder/File.aspx"}). Our HTTP module checks the "Request.Location" for each request and validates it against our specified Permission Rules in the database.

Here we present the second approach to extending the existing ASP.NET Role Based security model through an HTTPmodule which taps on to the events which are notified by the Web-Application during the lifetime of a request. Our HTTPModule should be able to validate and allow/deny the access to any location at run-time. (We are going to tap on to HTTPApplication.AuthorizeRequest event and inject our custom validation logic here). More information about ASP.NET Application's Page Life Cycle events and how we can inject our custom logic to Page Life Cycle through HTTPmodules here. In this way, the default role based security continues to work, but we have another layer of custom security.

5.jpg

Another good article explaining the control of Authentication using HTTPmodule is here. However, our HTTPModule rather extends the existing ASP.NET role based security and adds to it the Role based Permissions for each resource (aspx file) on our website.

This project is the narrowed down version of original ASP.NET MVC project. We are using Nhibernate for data persistence, hence Database portability to majority of databases should not be a problem. However we use MSSqlServer database here. If the schema is exported to other databases, this module should be able to work with other databases as well. However, it may also depend upon how your "Roles" and "Users" information is stored. The default ASP.NET SQL Membership, Role and profile providers have been used in this project.

Using the Code

This Module works on "Only If" basis. (i.e. Only if there is a permission rule configured (for a particular location), then only this module performs its validation. Otherwise the regular ASP.NET Page Life Cycle occurs.

working.jpg

To add a particular location for creating Permission, please add the location to the Actions Table first using the following form at the bottom of the Permissions Page:

AadhaarAddLocation.jpg

In the above case, the folder name "SuperAdmin" and the corresponding File Names "Permissions.aspx" and "UserDetails.aspx" have been added to the existing actions table. Once the Location has been added as above, it can be selected from the dropdown in the following form (Located at the top of the Permissions Page):

AadhaarCreatePermission.jpg

The method GetRolesForControllerAction checks if a particular UserId has an Exclusive access to a particular resource and sets the boolean out parameter HasUserPermission as true. If the user already has a User Level Permission to a particular resource (Controller+Action {Folder\File.aspx in our case}), no further validation is performed and the request is allowed to process normally.

However, if there is no exclusive User Based Permission created for a particular UserId, the permitted roles for the Specified resource are checked against User's Roles :

string[] permissions = Aadhaar.Data.ADHSecurityHelper.GetRolesForControllerAction
    (HttpContext.Current.User.Identity.Name, out HasUserPermission,reqFolder, reqFile);


                //If neither the user has a User Level Permission to the resource
                //And also the Configured Permissions for the resource are not empty.
                //Then check for Role Level Access
                if ((!HasUserPermission) && (permissions.Length != 0))
                    if (!((permissions.Length == 1) && (string.IsNullOrEmpty
            (permissions[0]))))      //Sometimes a singular string with 
                                //blank value was returned.
                    {
                        //If User has none of the Allowed Roles for a particular resource.
                        // Access will be denied. 
                        if (!MatchUserRolesToPermissions(HttpContext.Current.User, 
                permissions))
                        {
                            string message = string.Format("User {0} 
              does not have permission to access file {1} located at {2}"
                                , HttpContext.Current.User.Identity.Name, reqFile, 
                reqFolder);

                            System.Diagnostics.Trace.TraceInformation(message);

                            Utilities.TextLog(message);

                            throw new System.Security.SecurityException(message);
                        }
                    }
// 

The Database Tables used for the Permissions are as in the following figure. The Permissions are stored in aspnet_roleactions table either for the corresponding RoleId or UserId. RoleId and UserId columns are mapped to the ASP.NET Roles and Users tables as shown below:

AadhaarDb.jpg

Points of Interest

As mentioned above, this Module is a narrowed down version of ASP.NET MVC module, so it obviously can work with the ASP.NET MVC solutions as well. The NHibernatehelper class has been taken from one of the good tutorials here detailing the ASP.NET Nhibernate providers (basically using Mysql in the mentioned solution).

The default ASP.NET membership, Role and Profile providers have been used in this solution to persist User's Membership, Authorization and Profile information, as this module intends to extend the existing ASP.NET role based security. The code can definitely be configured to work with any other Custom Membership and Role Providers.

History

  • Published: 09-Nov-2011
  • Added AadhaarMVC: 12-Nov-2011

Important Links

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

Share

About the Author

amitthk
Software Developer (Senior)
Singapore Singapore
I love programming, reading, and meditation. I like to explore management and productivity.
Follow on   Twitter

Comments and Discussions

 
GeneralHow to chili peppers and weight reduction PinmemberMember 1103349424-Aug-14 21:27 
GeneralThanks for your help, I like your article very much. PinmemberMember 1103349424-Aug-14 20:35 
GeneralMy vote of 5 Pinmemberirulswift31-Jul-13 21:31 
GeneralRe: My vote of 5 Pinmemberokdone9-Aug-13 7:04 
GeneralMy vote of 5 [modified] PinmemberR&D Ninja26-Nov-11 6:50 
SuggestionGuys when you vote it down, please also let me know how should I improve it. Pinmemberokdone12-Nov-11 22:54 
GeneralRe: Guys when you vote it down, please also let me know how should I improve it. PinmemberR&D Ninja26-Nov-11 7:06 
GeneralRe: Guys when you vote it down, please also let me know how should I improve it. Pinmemberokdone28-Nov-11 5:58 
QuestionIn health-care ruling, precedent trumped politics PinmemberAimeili11-Nov-11 15:58 
AnswerRe: In health-care ruling, precedent trumped politics PinmemberDewey12-Nov-11 15:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141029.1 | Last Updated 12 Nov 2011
Article Copyright 2011 by amitthk
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid