I'm having an odd problem with Forms authentication. I have my own custom principal and identity classes, and after sign-in I set HttpContext.Current.User to this principal, as well as storing it in the cache (HttpContext.Current.Cache). It seems that after some time passes, the odd behavior begins. This is my AuthenticateRequest handler:
protected void Application_AuthenticateRequest( object sender, EventArgs e ) {
string userName;
var formAuthCookie = HttpContext.Current.Request.Cookies[ FormsAuthentication.FormsCookieName ];
var isAuthenticated = HttpContext.Current.Request.IsAuthenticated;
if ( isAuthenticated || formAuthCookie != null ) {
if ( !isAuthenticated ) {
var ticket = FormsAuthentication.Decrypt( formAuthCookie.Value );
userName = ticket.Name;
}
else {
userName = HttpContext.Current.User.Identity.Name;
}
var prin = (IPrincipal)HttpContext.Current.Cache[ userName ];
if ( prin != null ) {
HttpContext.Current.User = prin;
}
}
}
This always works fine; the custom principal is pulled from the cache and correctly set into the Current context's user.
The problem is that when I get to the page load, the Page.User property has a GenericPrincipal (with no roles) and a FormsIdentity. I have no idea where this is happening. Of course the page then doesn't work as the user is not in the proper role, although FormsAuth let them into a role restricted page.
Any ideas why the princpal I set in the AuthenticateRequest handler is being replaced?
Try this instead:
var formAuthCookie = Context.Request.Cookies[ FormsAuthentication.FormsCookieName ];
var isAuthenticated = Context.Request.IsAuthenticated;
if ( isAuthenticated || formAuthCookie != null ) {
if ( !isAuthenticated ) {
var ticket = FormsAuthentication.Decrypt( formAuthCookie.Value );
userName = ticket.Name;
}
else {
userName = Context.User.Identity.Name;
}
var prin = (IPrincipal)Context.Cache[ userName ];
if ( prin != null ) {
Context.User = prin;
}
}