Posts Tagged ‘Forms Authentication’

Defect in Microsoft Sample Code Using Forms Authentication

April 14, 2009 Leave a comment

If you are trying to use Forms Authentication and want to pass additional user data, there is a defect in the sample code provided by Microsoft.

The two errors are, (1) – when creating the FormsAuthenticationTicket, you must include the path of the cookie and (2) – you must create the authentication cookie using Response.Cookies.Add.  the code provided below works:

protected void btnLogin_Click( object sender, EventArgs e )
bool isAuthenticated = IsAuthenticated( txtUserName.Text, txtPassword.Text );

if ( isAuthenticated )
string roles = GetRoles( txtUserName.Text );
FormsAuthenticationTicket CLAC = new FormsAuthenticationTicket( 1, txtUserName.Text, DateTime.Now, DateTime.Now.AddMinutes( 60 ), true, roles, FormsAuthentication.FormsCookiePath );

string encryptedTicket = FormsAuthentication.Encrypt( CLAC );

Response.Cookies.Add( new HttpCookie( FormsAuthentication.FormsCookieName, encryptedTicket ) );

Response.Redirect(FormsAuthentication.GetRedirectUrl( txtUserName.Text, false ));


I tried changing the code, and instead of calling Response.Redirect using the FormsAuthentication.FormsCookieName method using FormsAuthentication.RedirectFromLoginPage().  This did log the user on, but the user data never showed up.  The problem in using the Microsoft example code was that the the auth cookie never got written.  Using the Response.Cookies.Add() method to create the cookie, and including the path when creating the auth ticket is what solved that problem.

The blog post that helped me out was

%d bloggers like this: