Wednesday, December 3, 2008

FormsAuthenticationTicket UserData disappears

I'm building an ASP.NET site and I had to implement the authentication/authorization subsystem. This is a standard code that is recommended by MSDN and several tutorials on the Web:

  1: if (loginResult == LoginResult.Successful)
  2: {
  3:   if(Request.QueryString["ReturnUrl"] != null)
  4:   {
  5:     Security.CreateAuthCookie ( this, txtUserName.Text );
  6:     FormsAuthentication.RedirectFromLoginPage ( txtUserName.Text, chkRememberMe.Checked );
  7:   }
  8:   else
  9:   {
 10:     Security.CreateAuthCookie ( this, txtUserName.Text );
 11:   }
 12: }

If username and password is correct, user can log in. If there is a return URL (this means he tries to access secured content), we have to create an authentication cookie and redirect user to that URL.  Security class and LoginResult enumerations are own implementations.

The code above will not work correctly if you are using own FormsAuthenticationTicket. Internet Explorer seems to work fine, but Firefox keeps showing the Login page. It seems there is a bug in the Framework and the UserData property (where we store e.g. roles) of the ticket will be empty (sometimes). The solution for the problem is changing line 6:

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

Article Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication on MSDN is correct, use that for implementing own Forms authentication.

2 comments: