Most of the time when you create a web site, you're going to use forms authentication or maybe windows along with one of the default membership, role, and profile providers. In my current frustrating task, I can't use any of the default providers. I'm stuck creating my own (which is actually fairly easy). However, I was constantly being annoyed by the fact that the Page.User property was not being created at all. Once again, this is extremely easy to fix, all we need to do is create a simple HttpModule:
#region Usings
using System;
using System.Web;
using System.Security.Principal;
using System.Web.Security;
#endregion
namespace PortalCore.Web.HTTPModules.Membership
{
class Membership:IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
}
void context_AuthenticateRequest(object sender, EventArgs e)
{
//Check if the user information is already filled out
if (HttpContext.Current.User == null || HttpContext.Current.User.Identity==null||string.IsNullOrEmpty(HttpContext.Current.User.Identity.Name)))
{
//Get the user's information here from whatever source
string []RoleNames=//Fill out with user's roles from your information
FormsIdentity Identity = new FormsIdentity(new FormsAuthenticationTicket(USERSNAME, true, 80000));
HttpContext.Current.User = new GenericPrincipal(Identity, RoleNames);
}
}
}
#endregion
}
}
All the code above does, is hooks into the application's AuthenticateRequest event. Every time the application wants to verify that the user is authenticated, it calls this event. So if you wanted, you can do some checking of your own at this point to see if the user is authenticated, redirect him, or deny access for certain pages from here. For our cases though we're just interested to see if the user information is filled out and if not we'll fill it out. This is done by first loading the user's information, then creating the forms authentication ticket, identity, and user object using that infomation.
Since I don't know how you are saving that information, I can't specify how to load it. It may be that you save the information in a cookie, session data, etc. That is the portion that you will have to figure out yourself. However, the Identity and User code is pretty straight forward once you have that. In this instance we're using forms authentication. We could easily use something else, it doesn't matter. However forms would probably be the easiest. Anyway, hopefully this post puts you on the right track for fixing this issue if you run into it. So try it out, leave feedback, and happy coding.
270d65a2-e56e-422f-892e-223e4344468e|0|.0