Why can't I delete this cookie? - c#

Okay, here is the 411 - I have the following event handler in my Global.asax.cs file:
private void Global_PostRequestHandlerExecute(object sender, EventArgs e)
{
if (/* logic that determines that this is an ajax call */)
{
// we want to set a cookie
Response.Cookies.Add(new HttpCookie("MyCookie", "true"));
}
}
That handler will run during Ajax requests (as a result of the Ajax framework I am using), as well as at other times - the condition of the if statement filters out non-Ajax events, and works just fine (it isn't relevant here, so I didn't include it for brevity's sake).
It suffices us to say that this works just fine - the cookie is set, I am able to read it on the client, and all is well up to that point.
Now for the part that drives me nuts.
Here is the JavaScript function I am using to delete the cookie:
function deleteCookie(name) {
var cookieDate = new Date();
cookieDate.setTime(cookieDate.getTime() - 1);
document.cookie = (name + "=; expires=" + cookieDate.toGMTString());
}
So, of course, at some point after the cookie is set, I delete it like so:
deleteCookie("MyCookie");
Only, that doesn't do the job; the cookie still exists. So, anyone know why?

you have to delete your cookie at the same path where you created it.
so create your cookie with path=/ and delte it with path=/ as well..

Have you checked the client-side and server-side cookie domains and paths to ensure they're the same?
Is one cookie secure and the other not?
Other than that, I would suspect server/client clock sync issues, as Erlend suggests.

Weird.. The code you pasted is almost verbatim to this: http://www.quirksmode.org/js/cookies.html which works fine..
I know you are using Ajax, but have you tried quickly knocking it to server side code to see if that works? This may help in figuring if it is a problem with the JS or something else (e.g mystery file locking on the cookie)?
Update
Just had a quick Google, looks like there may be issues with browser settings as well. I don't think your problem is the code here, it's more likely to be something else. I would suggest try the above as PoC and we can move from there. :)

I posted a js cookie util a week or so ago on my blog. This has worked for me on all "A Grade" browsers.
var CookieUtil = {
createCookie:function(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
},
readCookie:function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
eraseCookie:function(name) {
createCookie(name,"",-1);
}
};

Have you tried to use ;expires=Thu, 01-Jan-1970 00:00:01 GMT?

Also if a cookie domain was specified during the creation, I've found that you must also specify the cookie domain while trying to delete (expire) it.

Are we sure there's no code that sets the Cookie to HttpOnly (we're not missing anything above)? The HttpOnly property will stop (modern) browsers from modifying the cookie. I'd be interested to see if you can kill it server side like Rob suggests.

I assume you are calling this javascript on the browser side. Which browser are you using, how are you viewing the cookie to confirm it is still there?

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);
}

asp.net not saving my cookies

I know it's probably something simple, but I just can't figure it out. Note that I'm doing this on my own PC, not through a server (localhost) and I've considered that might be the issue, but I see nothing online about it being the case so maybe it's just a thought.
So I am trying to simply get a string and store it into a cookie and then read it later. Here's the lines of code that "saves" the cookie and its information:
HttpCookie cookie = new HttpCookie("userName", someInfo);
Response.Cookies.Add(cookie);
lblProof.Text = "Value: " + Request.Cookies["userName"].Value;
If I try this method, it fails. No information is shown on the lblProof. At first, I thought maybe someInfo didn't have anything in it (note it's a string). However, when I set the lblProof.Text to someInfo, it DOES show it. I've tried simply doing
Response.Cookies["userName"].Value = someInfo;
But that didn't work either. So what's causing this thing to not work at all? And yes, I've tried HttpContext.Current.Response and Request.

Access cookie from Client Side

I have set a cookie on the controller:
HttpCookie loggedIn = new HttpCookie("LoggedIn", "true");
Request.Cookies.Add(loggedIn);
I am trying to access this on document ready?
$( document ).ready(function() {
if ('#Request.Cookies["LoggedIn"]' != null) {
var loggedIn = '#Request.Cookies["LoggedIn"].Value';
console.log("Logged In " + loggedIn);
}
});
This keeps coming through as null?
Any ideas?
You're not actually accessing the cookie from the client-side JavaScript. Even though you're sending the cookie back to the browser, your code is ignoring that cookie and trying to access it via a Razor expansion. I guess that could work, but it seems like a roundabout way to do it.
You can access cookies from JavaScript though the document.cookie property, which is a ; delimited list of cookies.
Since you're using jQuery, a simpler way is to use the jquery.cookie plugin.
var loggedIn = $.cookie('LoggedIn');
Update: I just realized you're setting the cookie in the request. You should be setting it in the response:
Response.SetCookie(loggedIn);

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.

Chrome Cookie problem

I have the following c# code running on inside a logout page, via a "logout" button.
It works fine on ie and ff, but not on chrome. The issue is that chrome will not set the cookie. The value does not appear at all in the responce header. I have read some reports with similar issues on the net but no proper solution was proposed. Any help would be much appreciated. Thank you for your time. Here is the code that runs in the page:
public class LogOut : ExtendedControlBase
{
void RemoveCookie(string CookieName)
{
HttpCookie myCookie = new HttpCookie(CookieName);
myCookie.Expires = DateTime.Now.AddDays(-100);
Response.Cookies.Add(myCookie);
}
protected override void OnInit(EventArgs e)
{
Session.Remove("SiteUserEmail");
Session.Remove("SiteUserName");
Session.Remove("siteUserId");
Session.Remove("siteUserGroupId");
RemoveCookie("u");
Response.StatusCode = 301;
Response.AddHeader("Location", "/");
Response.Flush();
Response.End();
}
}
A few suggestions:
Try using something like Fiddler to see what exactly happening. My guess is actually the 'logout' link is not working on Chrome as expected.
Try setting the cookie header manually:
Response.AddHeader("Set-Cookie", "u=; expires=Fri, 31-Dec-1999 23:59:59 GMT");
Try setting test headers to check if they are really on the wire:
Response.AddHeader("X-Testing", "Testing");
Note: I haven't tried it. I assume setting arbitrary headers would work in Asp.Net.
My guess is that it's due to setting the expiration date in the past. Have you tried removing myCookie.Expires = DateTime.Now.AddDays(-100);? I believe it will still be treated as a session cookie without that value since the expiration date will not be set in the future.

Categories