C#, ASP.NET•Store the WindowsPrincipal Object in the Authentication Phase

Listing 2. Your program authenticates the WindowsPrincipal object from the Session object, then picks up WindowsPrincipal in the PreRequestHandlerExecute event on each subsequent request. The event fires right before the page starts processing the requests. Then the program stuffs the WindowsPrincipal object in the Thread.CurrentPrincipal and HttpContext.Current.User, making WindowsPrincipal available where expected during page processing.

//end of authentication routine
Session.Add ("info", wp);
FormsAuthentication.RedirectFromLoginPage 
	(TextBoxUser.Text, false);	
}
	
//in global.asax.cs

private void 
	Global_PreRequestHandlerExecute(object send, 
	System.EventArgs e) {

if(Thread.CurrentPrincipal.Identity.
	IsAuthenticated == true) {
	//replace Forms Principal with Windows 
	//Principal
	GenericPrincipal gp = 
		(GenericPrincipal)Thread.CurrentPrincipal;
	Thread.CurrentPrincipal = 
		(WindowsPrincipal)Session["info"];
	HttpContext.Current.User = 
		(WindowsPrincipal)Session["info"];
	Session["info"] = gp;
}
}

private void 
	Global_PostRequestHandlerExecute(object send, 
	System.EventArgs e) {
//Restore the original Principal, just in case
WindowsPrincipal wp = 
	(WindowsPrincipal)Thread.CurrentPrincipal;
Thread.CurrentPrincipal = 
	(GenericPrincipal)Session["info"];
HttpContext.Current.User = 
	(GenericPrincipal)Session["info"];
Session["info"] = wp;
}