I am having a problem with my asp.net web application and Chrome. When I close my Chrome browser window, it does not clear out cookies. This means that if I log into my web application using forms authentication, and then close and reopen the browser window, it shows I am still logged in!
I read that this may be a Chrome bug, but there must be some way around it.
I found this post and would like to run the following code from it when the browser window is closed:
FormsAuthentication.SignOut();
Session.Abandon();
// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);
My question is, is there a browser closed event handler that I can specify somewhere in my code? Perhaps Application_End
in the Global.aspx file? Or is that not what it is meant for?
Or is there another way to solve this issue?
Thank you.
Here is what my code looks like:
private void Login_Click(Object sender, EventArgs e)
{
// Create a custom FormsAuthenticationTicket containing
// application specific data for the user.
string username = UserNameTextBox.Text;
string password = UserPassTextBox.Text;
bool isPersistent = false;
if (Membership.ValidateUser(username, password))
{
string userData = "ApplicationSpecific data for this user.";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
// Redirect back to original URL.
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}
else
{
Msg.Text = "Login failed. Please check your user name and password and try again.";
}
}
Only replace isPersistent
with the value of checkbox.Checked
which is false
by default.
EDIT:
Another annoying thing which is what may be going on is from [this] link where the top answer says:
It also matters which browser you use. Chrome has the ability to run in the background, and that keeps Session Cookies around until their timeout is hit -- they are not dropped when the browser is closed (I found this out the hard way).