Using Custom Principal with Forms Authentication in ASP.NET

FormsAuthentication is the most generic authentication for securing ASP.NET applications. By default, it assigns a GenericPrincipal to HttpContext.Current.User (as well as Thread.CurrentPrincipal) with a FormsIdentity object.
If we need to use a custom implementation of IIdentity and IPrincipal with forms authentication, we simply need to hook the AuthenticateRequest event in global.asax.cs and assign our CustomPrincipal to HttpContext.Current.User.

Here’s how I like to do it:
In my login page, after validating the user credentials, I simply store the username in my FormsAuthentication ticket like this:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
	//validate from some data store here
	SecurityManager securityMgr = new SecurityManager();
	if ( SecurityManager.Authenticate( Login1.UserName, Login1.Password )
	{
		//User authenticated, now store UserName in Forms Authentication ticket
		FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
	}
}

My implementation of CustomIdentity requires a username to populate itself. This way, I am able to use the following code in my global.asax.cs:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
	if (Request.IsAuthenticated)
	{
		//get the username which we previously set in
		//forms authentication ticket in our login1_authenticate event
		string loggedUser = HttpContext.Current.User.Identity.Name; 

		//build a custom identity and custom principal object based on this username
		CustomIdentitiy identity = new CustomIdentitiy(loggedUser);
		CustomPrincipal principal = new CustomPrincipal(identity);

		//set the principal to the current context
		HttpContext.Current.User = principal;
	}
}

We’re done. Now we will get HttpContext.Current.User as well as Thread.CurrentPrincipal set to our CustomPrincipal object anywhere in our ASP.NET application; screenshot below(click to enlarge):

Setting current context to CustomPrincipal

The advantage we get is that now we can use declarative security checks to protect our methods, like this:

PrincipalPermission(SecurityAction.Demand, Role="MyCustomRole")]
public string MySecureMethod(int parameter)
{
	// If anyone not in "MyCustomRole" tries to call this method,
	// a SecurityException is thrown
	return string.Empty;
}
Advertisements

11 Responses to “Using Custom Principal with Forms Authentication in ASP.NET”

  1. tmont Says:

    Note that if you’re using a role provider as specified in the web.config, you will need to override Application_PostAuthenticateRequest rather than Application_AuthenticateRequest, or else you will see a RolePrincipal every time.

    This frustrated me for a few hours. 🙂

  2. Syed Mehroz Alam Says:

    Thanks for sharing, Tommy.

  3. ASP.NET MVC Archived Buzz, Page 1 Says:

    […] to Vote[Del.icio.us] Using Custom Principal with Forms Authentication in ASP.NET « Mehroz’s Experiments …Wednesday, June 22, 2011 from […]

  4. tanisha Says:

    😦 nothing’s usefulll….

  5. tanisha Says:

    please provide me with some more detailde examples regarding Custom Forms Authentication…

  6. http://tinyurl.com/winthelan00437 Says:

    This particular posting, “Using Custom Principal with Forms Authentication in ASP.

    NET Mehrozs Experiments” ended up being terrific.
    I am printing out a reproduce to demonstrate to my personal buddys.
    Thanks,Danielle

  7. http://tinyurl.com/slavgavin40062 Says:

    “Using Custom Principal with Forms Authentication
    in ASP.NET Mehrozs Experiments” was in fact a extremely great
    blog, . I hope you keep creating and I’ll continue to keep browsing! Thanks for the post -Joseph

  8. Custom MembershipProvider, Principal and Identity - Ole Michelsen Says:

    […] we can replace them with our own IPrincipal and IIdentity! In global.asax we overwrite the generic objects, with our own versions that contains our extra […]

  9. Veysel Özdemir Says:

    Thank you very much. Your article is simple and compact. You saved me today

  10. Jordan Says:

    Hi Syed, Thank you so much, Your article it´s great, but I have a doubt, the Application_AuthenticateRequest event is fired every request, so if you build a custom identity from data base information, you need go to request a data base every time, How it’s possible make only one request to the data base?,

    Regards

  11. chaqueta peuterey Says:

    Hoy en día el vestido de línea de la marea es la clase de tipo dulce, el color rosa, chaqueta de estilo de párrafo corto, vestido con capa suave y grueso, muy agradable. Las personas con una falda de hojas de loto, a la temporada tranquila trae un ambiente juvenil similares. El diseño se parece a la parte inferior de la contracción, lo que hace el cuerpo más bien proporcionada hermosa. Usar faldas cortas, botas planas, las personas con más energía, las piernas se sienten frías, se puede poner un par de pantimedias.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: