How to delete or expire cookie in Chrome using asp.net - c#

This is one of those dumb questions. The answer should be simple, but it doesn't seem to be working. Anyone have any ideas where else for me to look for some rep?
I'm adding a cookie on a button click
var impersonationCookie = new HttpCookie("UserImp_ImpAuid");
impersonationCookie.Value = Encode64(auidToImpersonate);
impersonationCookie.Expires = DateTime.Now.AddDays(1d);
impersonationCookie.Path = "/";
Page.Response.Cookies.Add(impersonationCookie);
I'm expiring a cookie and clearing the value on a page_load
HttpCookie currentUserCookie = HttpContext.Current.Request.Cookies["UserImp_ImpAuid"];
HttpContext.Current.Response.Cookies.Remove("UserImp_ImpAuid");
currentUserCookie.Expires = DateTime.Now.AddDays(-10);
currentUserCookie.Value = null;
HttpContext.Current.Response.SetCookie(currentUserCookie);
Chrome (v 69) still shows the cookie with the value MDAwMDM5OTk2 and with an expiration date of When the browsing session ends.
I've tried plenty of variations from other questions
Delete a cookie on signing out
How to delete a cookie from .net
How to delete cookies on an asp.net website

As mentioned in the comment, This could be because chrome setting "Continue where you left off".
You can cross check in a different browser.
Chrome Doesn't Delete Session Cookies

Related

How can I delete this cookie? ASP.NET MVC

I try to delete this cookie:
First of all a bit of background. This is a token for verification on different sites within the same domain. I make the central login page. This page is working fine, except the log out. Every other cookie, I want to delete, gets deleted by JQuery cookie $.removeCookie('cookieName'). And I know, I can't delete this from the JavaScript, because of the secure-flag.
So I tried deleting it from a controller method. I call this method via ajax from JavaScript.
$.ajax({ur:'/Login/ExpireToken'})
I can see that it works in the Chrome Console Network Tab.
public void ExpireToken()
{
Response.Cookies.Remove("crowd.token_key");
}
But this, I don't know why, makes a new cookie, with the same name, empty value, the whole domain of the login page and no flags set.
So I tested, if the backend can find the cookie I want.
public string ExpireToken()
{
return Response.Cookies["crowd.token_key"].Value;
}
It returns the correct value and doesn't create a new/false one.
After this I tried to set the expires field to one day in the past or to now. I don't know, why this should work, because the expiration date of this cookie is already in the past.
public void ExpireToken()
{
Response.Cookies["crowd.token_key"].Expires = DateTime.Now.AddDays(-1d);
}
And guess what, it doesn't work. It does literally nothing.
Other ways that don't work
if (Request.Cookies["crowd.token_key"] != null)
{
var c = new HttpCookie("crowd.token_key");
c.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(c);
}
As per the doc, you are doing things right in your las attemp, the one setting the expiration date to yesterday. Quote:
The technique is to create a new cookie with the same name as the
cookie to be deleted, but to set the cookie's expiration to a date
earlier than today. When the browser checks the cookie's expiration,
the browser will discard the now-outdated cookie
I would put a breakpoint and debug to check cookie names, if everything is fine, perhaps the web browser is missbehaving.
HttpCookie aCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i<limit; i++)
{
cookieName = Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(aCookie);
}

Ensuring forms authentication logout on browser close

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).
2
There is no browser closed handler, how could there be? Once the page is done being served the connection is closed. You have no idea if a user browses away from the site, closes the browser, or let's it sit there for a day. You would have to use client-side code to call a service to handle this and the client-side code to do this is unreliable enough to make it useless.
When you set the authentication cookie, make sure the persistent option is false.
Also, when you close your browser ensure that you are closing all browser windows. If you have multiple browser windows they will share the same cache for cookies so things like the session cookie are still alive because of this and lead you to believe the authentication is kept alive by the server when it's really the browser.

How do I manually delete a cookie in asp.net MVC 4

I need to delete authentication cookie manually (Instead of using FormsAuthentication.SignOut whcih for some reasons does not work). I tried
System.Web.HttpContext.Request.Cookies.Remove(cookieName); // for example .ASPXAUTH
System.Web.HttpContext.Response.Cookies.Remove(cookieName); // for example .ASPXAUTH
FormsAuthentication.SignOut(); // I don't know why this one does not work
Neither of those command work. In fact Response cookies are empty and request cookie contains the cookie I want to delete when the following commands are executed it no longer contains the cookie I deleted but in browser the cookie still exists and I am able to do things that authorized users can even after signing out.
Try:
if (Request.Cookies["MyCookie"] != null)
{
var c = new HttpCookie("MyCookie")
{
Expires = DateTime.Now.AddDays(-1)
};
Response.Cookies.Add(c);
}
More information on MSDN.
c.Expires = DateTime.Now.AddDays(-1);
This does not clear cookies instantly.
Use this: c.Expires = DateTime.Now.AddSeconds(1);
This will clear cookies instantly.

Cookies don't persist after refresh

I am using c# and mvc. I am trying to write a cookie to the user browser. But after a refresh of the browser the cookie disappears.
This is my code for writing the cookie:
movieCookie = new HttpCookie(cookieName);
movieCookie.Value = "test;
movieCookie.Expires = DateTime.Now.AddDays(30);
//add the cookie
HttpContext.Current.Response.Cookies.Add(movieCookie);
and the one for reading the cookie:
//check if such cookie exist
HttpCookie movieCookie = null;
if (HttpContext.Current.Request.Cookies.AllKeys.Contains(cookieName))
movieCookie = HttpContext.Current.Request.Cookies[cookieName];
Another thing to add is that when I searched "AllKeys" like so:
HttpContext.Current.Request.Cookies.AllKeys
it shows an empty string array, for some reason.
any ideas?
Some possibly silly questions
Check your web-servers time and date, are they set correctly, if they are (in your case) 2 years out it will expire cookies immediately.
Check that cookieName is the same
Check that after setting the cookie to the response your not redirecting before the cookie is set. For a cookie to be set you need to set headers and push them out.
I solved it. It appears that in MVC the "return view" after the cookie creation, cause the cookie not to be saved.

Cookie is not getting deleted in IE 8

I'm trying to delete a cookie but somehow it is not getting deleted in IE 8
This is the code i'm using
HttpCookie userCookie = Request.Cookies[cookieName];
if (userCookie != null)
{
userCookie.Expires = DateTime.Now.AddDays(-1);
if (!string.IsNullOrEmpty(cookieDomain))
userCookie.Domain = cookieDomain;
Response.Cookies.Add(userCookie);
}
It is working fine in firfox and chrome .
Suppose the name of the cookie is testcookie. We created this cookie from xyz.com and we set the domain of the cookie as ".xyz.com". Now we are deleting or expiring this cookie from subdomain.xyz.com. We are deleting the cookie with the code we have mentioned above.
Check your cookies. You may have two cookies called "testcookie" or whatever. This has happened to me before and caused a lot of pain. You can check quickly by typing javascript:alert(document.cookie) into the address bar.
If you have got duplicate cookies delete all your cookies and start testing again. I.e. setting your testcookie, then on another request try expiring it again how you were before.

Categories