Reputation: 5536
I noticed that when I restart my ASP.Net application, logged users' credentials are remembered and they may find themserves automatically logged in.
This behaviour is unwanted as long as the users' session variables, set at login time, are not carried along.
So, how can I "forget" all sessions on the application start?
I see that I can't use Session.Abandon()
in the Application_Start
event.
Upvotes: 4
Views: 6610
Reputation: 143
Use this code when a new session is started i.e. add it in Global.asax
#region remove all cookies
string[] myCookies = Request.Cookies.AllKeys;
foreach (string cookie in myCookies)
{
Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
}
#endregion
Upvotes: 1
Reputation: 124726
Assuming you're using Forms Authentication, it's expected behaviour: the user still has a valid FormsAuthentication cookie even if your application has restarted.
If you really want to log them out, you just need to call FormsAuthentication.SignOut
.
But I'd question the need to do this - why force the user to enter his credentials again? If you've lost state that was stored in Session, you may need to redirect to a Home page or something, but no need to make the user log in again.
Upvotes: 0
Reputation: 6123
After restarting Session exists ? How it is possible? Probably you are using Session state server or Sql server. You can not use Session.Abandon() in the Application_Start event because when application starts, at that time, there is no session exists. Call Session.Clear() or Session.Abandon() method in the Application_End event so when application restarts it must clear all the session..
Upvotes: 1
Reputation: 5967
you must clear you cookies like this :
foreach (string key in Request.Cookies.AllKeys)
{
HttpCookie cookie = new HttpCookie(key);
cookie.Expires = DateTime.UtcNow.AddDays(-7);
Response.Cookies.Add(cookie);
}
EDTI : doing this all of your cookies will be expired.and the browser will attempt to delete all you'r cookies.and this will result in not remembering login state of your users.
hope this helps.
Upvotes: 0