Jeff Garoutte

c# .net and anything else that happens across my desk

Extending the ASP.Net Security model to use rights : Part two - the IHttpModule

In part one - IPrincipal, I talked about the right and IPrincipal objects needed to add "right" based security to asp.net applications in addition to role based security.

There are a few things we need to do to get ready to build the IHttpModule.  First we need something to give us a list of rights for a user.  To do this we will create a quick "RightManager" class.  We will create a static method "GetRightsByUserName" to return a list of Right objects for a given user name.  Really this class could also manage creating, editing and deleting rights along with assigning rights to roles, or users but that is outside of the scope of this article.  For a production system this class would likely use a provider model to connect to a data store and return the list of rights specific to the user base on their role membership.  For our purposes we will return the same right list for any user with a name starting with the letter J.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectHelpDesk.Security
{
    public static class RightManager
    {
        public static List<Right> GetRightsByUserName(string userName)
        {
            List<Right> result = new List<Right>();
            Right someRight = new Right();
            someRight.Id = new Guid();
            someRight.RightName = "SVN Access";

            if (userName.ToLower().StartsWith("j"))
                result.Add(someRight);
            return result;
        }
    }
}

The IHttpModule is where we do most of the heavy lifting. Because the code the gets the rights back from the user name is isolated in the Rights Manager class the amount of code in the module is really rather small.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ObjectHelpDesk.Security
{
    public class RightsHttpModule : IHttpModule 
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.PostAuthenticateRequest += new EventHandler(context_PostAuthenticateRequest);
        }

        public void context_PostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication context = (HttpApplication)sender;
            if ((context.User != null) && (context.User.Identity.IsAuthenticated))
            {
                List<Right> rights=RightManager.GetRightsByUserName(context.User.Identity.Name);
                RightPrincipal newPrincipal = new RightPrincipal(context.User, rights);
                HttpContext.Current.User = newPrincipal;
                System.Threading.Thread.CurrentPrincipal = newPrincipal;
            }
        }

        #endregion
    }
}

When the When the module is loaded it will fire the Init method.  This wires the PostAuthenticateRequest event to our custom event handler "context_PostAuthenticateRequest".  The reason we use the PostAuthenticateRequest event is it allows us to alter the security principal after the membership and roles system has already processed and authenticated the user.  Because the user is already authenticated  at this point, the method used to authenticate them does not come into play and we can concentrate on getting the rights loaded.  Yes, this method of adding rights works with both Forms and windows authentication. We create the new RightPrincipal passing in the current principal and the list of rights for the user.  We than add the new principal to the Current HttpContext and the Thread.  The Principal of the thread is important and needs to be set as well.

Next we add the IHttpModule to the web.config.  The order you list the modules in the httpModules section of the web.config is important.  It determines the order of execution for the events in the modules. 

image

Now you can debug your web site project and login with various user accounts to check their rights.

While this code works, there are things I would take the time to clean up before using it in a production system. 

  1. The RightManager should be fleshed out and working with the ability to create, delete, edit and assign/revoke rights.
  2. The context_PostAuthenticateRequest method in the HttpModule should always create and hook in a RightPrincipal if it is not already one.

 Part 3 : Code security by Right, Attributes

If you are getting lots of SQL traffic for each request (the debugger stops in the module a lot), read this post!

kick it on DotNetKicks.com

Posted: May 23 2008, 02:44 by jeff | Comments (14) RSS comment feed |
Filed under: Security
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Comments

Lucio SAccal Argentina said:

Lucio SAccal

Is not usual for me to comment in blogs. but this article deserves to be appreciated.
VERY GOOD POST!!
VERY HELPFULL.
Thanks.
Lucio
  

# December 05 2008, 21:29

Brad said:

Brad

When I test this I get "Could not load file or assembly" on <add name="RightsModule" type="ObjectHelpDesk.Security.RightsHttpModule, ObjectHelpDesk.Security" />

Is there something else I'm missing that is not described?

# February 06 2009, 13:57

Brad said:

Brad

When I change to <add name="RightsModule" type="ObjectHelpDesk.Security.RightsHttpModule" />

I no longer get the "could not load file or assembly" error.

# February 06 2009, 14:04

Jeff United States said:

Jeff

@Brad

type="ObjectHelpDesk.Security.RightsHttpModule, ObjectHelpDesk.Security"

the part after the , is the assembly name (often the dll name without the .dll extension)

If you changed the namespace you would need to change the type to use the correct namespace and class name.

# February 20 2009, 11:22

tipsonlips.net said:

pingback

Pingback from tipsonlips.net

ASP.NET Membefrship Resources

# March 30 2009, 21:25

JB United States said:

JB

Wow, talk about just what I was looking for. However, I'm having a slight problem. In my version of the RightManager class I'm going to the database to look up the rights for a user. This causes SQL to fire off for each and every request, including the GET's for .css, .js, and image files.

While your suggestion works great, in the real world generating the same exact SQL calls 17 times in a row to load a single page just isn't very efficient. Can you offer any suggestions on how to overcome that problem.

# June 06 2009, 13:34

Jeff United States said:

Jeff

@JB,
There is a discussion about that issue in the comments of part one www.jeffgaroutte.net/.../...-one---IPrincipal.aspx

Also, Im going to post about that issue... hopefully this weekend; but you should have an email that covers it in the meantime.

# June 13 2009, 14:49

Joe Germany said:

Joe

Hi Jeff,
regarding the web.config picture. Do I guess right, that it was:
<add name="RightsHttpModule" type="System.Web.Security.RightsHttpModule"/>

Thanks for great article series!

# October 22 2009, 09:17

Lasse Denmark said:

Lasse

Hi,

thanks for a great artivle.

Could you please change the image link to a working one? This link no longer works: www.jeffgaroutte.com/.../image_thumb.png

# November 24 2009, 01:05

watch vampire diaries United States said:

watch vampire diaries

I admire what you have done here.



Regards
Palin



# December 05 2009, 18:29

lexus dealerships in new york United States said:

lexus dealerships in new york

I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.



Regards
Vish


# December 08 2009, 17:57

hip hop reviews United States said:

hip hop reviews

Hi nice to read this I realy like to



Regards
Hington

# December 14 2009, 18:50

Fatcow Review United States said:

Fatcow Review

Should I get a Dedicated Hosting?  I am using godaddy but they keep disabling my account due to high server overload. Im getting about 2,000 UV a day. What hosting should I get?

# February 27 2010, 06:06

wow mobiles United States said:

wow mobiles

WoW Mobiles is awesome! I get free mobile service with t-mobile because I refered 3 people to wow. You can too!

# March 03 2010, 02:06

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
Loading