Asp.net user authenticated after signout.

The Asp.net Membership relies on cookies to store the FormAuthentication ticket of a user, this means that we have to remove the cookie in order to signoff from our application.

When an user is logged a cookie containing the encrypted ticket is stored on the client machine:

public void CreateUserCookie(string username)
{
  //Expiration of the cookie
  DateTime expiration = DateTime.Now.AddMonths(3);
  //Expiration of the ticket
  FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(username, false, 10);
  string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
  HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
  authCookie.Expires = expiration;
  HttpContext.Current.Response.Cookies.Add(authCookie);
}

*Note that the expiration of the cookie and the expiration of the authentication are different. A cookie can be stored on the client for as long as we want (es 3 months) while we want the user to be authenticated on the site for 10 minutes only.

Here is the logout:

FormsAuthentication.SignOut();
Roles.DeleteCookie();
Session.Clear();
FormsAuthentication.RedirectToLoginPage();

*Note that clearing the session doesn’t affect the cookie and so the authentication. Forms authentication and session are not related at all, if a browser doesn’t support cookies the ticket is stored in the url.

The issue of having the user always authenticated on the website even after a signout happens because the FormsAuthentication.SignOut() method has failed and we don’t get any notification.

One of the causes can be a wrong configuration of the Forms authentication in our web.config. By default Asp.net expect the authentication cookie to be in a different folder from the one we’ve used to create the cookie manually.

<forms loginUrl="/Pages/work-with-us.aspx" protection="All" timeout="10" name="ProjectX.Web" requireSSL="false" slidingExpiration="true" path="/FormsAuth" enableCrossAppRedirects="false"/>

Remove the “path” parameter to ensure the cookie location is the same of your cookie one. * Note that the “name” parameter define the name of the authentication cookie (FormsAuthentication.FormsCookieName )

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s