Jan 12 2006

Getting the authenticated username

Posted by admin under ASP.NET articles

This article is a followup on these earlier articles



Ok, after reading those articles we know how to limit access to a specific location on our website, but what about a more finegrained control. I mean, maybe some people should get to see some extra items in the menu or something, while other shouldn't.

Assuming you have a database with some kind of usertype column (superadmin/admin/readonly for example) the problem now is - all we know now is that all people accessing our protected area are indeed validated against our database - but we can't control it any more.

I mean what if we (in our code that is) need to make a distinction between Joe and Sarah - both are valid users - but lets say that Sarah should be able to save information but Joe should not (read only viewer)?

The key to success is simple: 

 System.Web.HttpContext.Current.User.Identity.Name 

 gives you the loginname used - whether it's through the loginform or through a "remember me cookie".

Now lets look at the kind of code I usually use:



    public static ObjClasses.User CurrentUser 
    { 
        get 
        { 
            if ( System.Web.HttpContext.Current.User == null ) 
                return null; 
            string strUser = System.Web.HttpContext.Current.User.Identity.Name; 
            if ( strUser == "" ) 
                return null; 
            if (System.Web.HttpContext.Current.Items["CurrentUser"] == null ) 
                { 
                ObjClasses.User oUser = new SupportMentor1.ObjClasses.User(); 
                if ( oUser.OpenEmail( strUser ) == false ) 
                    return null; 
                System.Web.HttpContext.Current.Items["CurrentUser"] = oUser; 
                } 
            return System.Web.HttpContext.Current.Items["CurrentUser"] as ObjClasses.User; 
        } 
    }  


To get the current user (of the user type we define in our database - which might contain a sort of usertype column - superadmin/admin/readonly etc) we use System.Web.HttpContext.Current.User.Identity.Name which ASP.NET so kindly puts the validated user id into - and I repeat - regardless of the user logged in through our form or through the cookie.

I do some caching (read more about that here) so only one database access is made per page request, but as you can see I use the System.Web.HttpContext.Current.User.Identity.Name as the key into my USER database table, by oUser.OpenEmail. Cause in this particular system the username is their email.