Issues overwriting a cookie - c#

Client has a site at a.url.com. Client creates a cookie with host as ".url.com" and path as "/". Client redirects to us at b.url.com. Client has a coding issue that requires us to delete the cookie (long story).
The following code is not adjusting the expiration at all in our test or production environments but is working fine locally.
if (Request.Cookies["cookie"] != null)
{
HttpCookie myCookie = new HttpCookie("cookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Any ideas?

We've figured it out. We needed to add one line of code to manually set the domain. Makes total sense now.
if (Request.Cookies["cookie"] != null)
{
HttpCookie myCookie = new HttpCookie("cookie");
myCookie.Domain = ".url.com";
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}

is this a third party cookie? If so, the default security settings in IE will prevent cookie writing in the "internet" zone but it is allowed in your local zone.

Here's a hack. I am just posting this in case you find out that you cannot do what you want due to some security issue preventing you handling the issue on the second site.
You could send a request to the first site to clear the cookie via redirect and have that site bounce the user back again. Like I said, this is very hackish (or I suppose marketing would call it inter-site cooperative security feature).
Hopefully, there's a better approach, but at least you have an alternative if no other ones are forthcoming.

If you cannot get it working in C# you might want to consider seeing if you can manipulate the cookies in javascript.
Gary

Related

How to delete old cookies after changing to manual machine key and wildcard cookies ASP.NET MVC 4.5

How to delete cookies in ASP.NET after changing machine key but staying on the same sub-domain?
Currently we have cookies on example.domain.com, but we need to move to wildcard cookies (.domain.com) so that the cookie also work on foo.domain.com. In order to do this, we have manually set a machine key to encrypt/decrypt the asp.net login cookie. Problem is that people that already have the old cookie, will now receive a CryptographicException when trying to access the site (as it tries for some reason to decrypt the old cookie). We have changed the name of the cookie, but it did not help - still receives the error. So we figured out that we wanted to delete all the old cookies. We try do do this on the login site with the following code:
var myCookies = Request.Cookies.AllKeys;
foreach (var cookieName in myCookies)
{
var cookie = Request.Cookies[cookieName];
if (cookie == null) continue;
cookie.Value = "written " + DateTime.Now;
cookie.Expires = DateTime.Now.AddYears(-1);
cookie.Domain = "example.domain.com"
Response.Cookies.Add(cookie);
}
We reach the code, and it runs, but the cookies still remain when inspecting in google chrome resources. So obviously the deletion did not work. We have tried several different ways (adding path ="/", setting cookie.Value to cookie.Value etc. For some strange reason the cookies still remain and we are unavailable to delete them.
So to get back to the original question, how an we delete cookies in ASP.NET MVC 4.5 after changing to a wildcard domain on our cookies and explcitly stating the machine key in the web.config?
If you don't absolutely have to use the same ticket name, your solution should work if you changed the name of the FormsAuthentication cookie:
<forms name=".YOUR_NEW_COOKIE_NAME" /> **
** Note that I've omitted the other attributes from the tag shown, so you wouldn't want to copy/paste it verbatim.
Turns out that by removing cookie.Domain, it managed to delete the cookies. I recon this has to do with the fact that in order to overwrite a cookie, you need to be as specific as possible when adding the replacing cookies. Seeing as the former cookies was added without specifying domain nor path, this is the most specific.
The code that ended up working in this scenario, was therefor:
var myCookies = Request.Cookies.AllKeys;
foreach (var cookieName in myCookies)
{
var cookie = Request.Cookies[cookieName];
if (cookie == null) continue;
cookie.Value = "written " + DateTime.Now;
cookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie);
}

why not using Request.Cookies.Clear() in ASP.NET web forms?

I searched here on the stackoverflow about removing all cookies from site, but couldn't find a single answer suggesting the use of Request.Cookies.Clear() method.
What's the difference between:
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
and:
Request.Cookies.Clear();
Thanks in advance!
and sorry for my bad language, English is not my native!
Calling Remove or Clear will remove it from the server side collection held by Request.Cookies (which is a copy of the cookies your client sent to you). However that does not cause the server to instruct the client browser to remove the cookie. To do that you need to set the timeout as you have indicated above (see MSDN - How To: Delete a Cookie for the official guidance).

.Net cookies keep coming back with expiration of zero

I am having trouble with the .Expires cookie attribute. It keeps coming back with 01/01/0001 12:00 AM, when I read the cookie back.
Here is the code. I added in the retrieve just below the save solely for debugging purposes. The save and retrieve happen in different places in the same file. I purposely did not specify a Domain, as I want the cookie to exist site wide.
The data shows up nicely, just not the expiration.
Note: I am testing under Visual Studio 2012 running under local host using .Net Framework 4.
System.Web.UI.Page oPage = this.Page;
HttpCookie oCookie = new HttpCookie("UserData");
// Set the cookie value.
oCookie.Secure = false;
oCookie["Field1"] = strField1;
oCookie["Field2"] = strField2;
oCookie.Expires = DateTime.Now.AddDays(1);
// Add the cookie.
oPage.Response.Cookies.Add(oCookie);
// Get the cookie.
oCookie = new HttpCookie("UserData");
oCookie = oPage.Request.Cookies["UserData"];
The browser will not send anything to the server except the cookie name and value. All of the other properties (expires, domain, path, httponly, ...) cannot be retrieved on requests after the cookie has been set.
The more accepted way to deal with this is to redirect the user to a login page when they try to access a protected resource and display some message along the lines of "You need to log in to view this page. If you were previously logged in, your session may have expired."
(Also note that you should be re-setting the cookie on every request, so that the user will not be logged out if they continue to use the site. It's not clear from your code whether you are doing this or not.)
I was just doing some more Google searching on my problem and saw this link, another posting here on Stackoverflow.
Cookies are always expired
I am also validating using the construct:
if (cookie != null && cookie.Expires > DateTime.Now)...
As several pointed out, expiration checking happens, if you can no longer retrieve the cookie. That is seriously dumb on whomever constructed this architecture. Yes, maybe there should be RequestCookie and ResponseCookie, the difference being ResponseCookie has no Expiry date.
The person who resopnded to me taught me that it is not just expires but other fields too.
In C# code, if using Form Authentication, You can find if cookie is persistent using below code
bool IsCookiePersistent = ((FormsIdentity)User.Identity).Ticket.IsPersistent;
Here Ticket will return the FormsAuthenticationTicket which has Expiration DateTime property.

how to remove cookies from browser in asp.net c#, SO answers NOT working

I'm trying to remove cookies using C# when a user logs out. The code suggestions listed here: remove cookies from browser do not work. I put several of them together in desperation and they are not working.
if (Request.Cookies["loginidcookie"] != null)
{
HttpCookie myCookie = new HttpCookie("loginidcookie");
myCookie.Value = String.Empty;
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");
}
Response.Redirect("logout.aspx");
So not only am I overwriting the value of the cookie with an empty string, I am setting it to expire yesterday AND removing it from the list of cookies. Yet when I run this code then hit the back button and reload, the cookie is still there with its original value. So how do I get rid of it?
Thank you
Try this instead:
string cookieName = "loginidcookie";
if (Request.Cookies[cookieName ] != null)
{
var myCookie = new HttpCookie(cookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Response.Redirect("logout.aspx", false);
Note (from here):
You cannot directly delete a cookie on a user's computer. However, you
can direct the user's browser to delete the cookie by setting the
cookie's expiration date to a past date. The next time a user makes a
request to a page within the domain or path that set the cookie, the
browser will determine that the cookie has expired and remove it.
You are adding the Cookie and then Removing it from the collection before the response is sent so you are effectively doing nothing.
HttpCookie myCookie = new HttpCookie("loginidcookie");
... and then below
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");
If you change the cookie to expire yesterday, you need to leave the cookie in the collection so that the browser takes care of deleting it once it sees the cookie has been updated with an expiration date in the past. In other words, don't call Response.Cookies.Remove("loginidcookie");
Try RedFilter's solution but use Server.Transfer() or Server.TransferRequest() instead of Response.Redirect() which it seems doesn't always let those cookie responses happen due to a possible bug.
Are you checking the cookie after closing the browser? Or reloading the page in the same browser?
If you are opening the page in the same browser you will see the cookie which is expired, but if you opened the new browser and try to access the page again, you would not get the cookie.

How do Cookies Work in ASP.NET?

The website where I work is made up of several projects (written in several languages). Right now we have to use some awkward code in query strings and session variables to keep a person logged in when they go from project to project. Since cookies are domain specific we're trying to convert to them since they can be set in one project using one language yet be accessed by a different project (on the same domain) using a different language.
However I am having problems changing the value of a cookie and deleting them. Or to be more specific, I'm having trouble having any changes I make to a cookie stick.
For example in my logout code:
if (Request.Cookies["thisuserlogin"] != null)
{
HttpCookie myCookie = new HttpCookie("thisuserlogin");
myCookie.Value = String.Empty;
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Response.Cookies.Set(myCookie);
litTest.Text = myCookie.Expires.ToString() + "<br />" + Request.Cookies["thisuserlogin"].Expires.ToString();
}
I wind up with one line being yesterday and the next line being 1/1/0001 12:00:00 even though they SHOULD be the same cookie. So why is it that even though the cookie was set, it's value did not change? Is there a way to force the user's computer to update a cookie's value, including deletion?
Thank you very much.
PS Any URLs you can provide to give an easy-to-understand primer for cookies would be appreciated.
http://msdn.microsoft.com/en-us/library/ms178194(v=vs.100).aspx
if (Request.Cookies["thisuserlogin"] != null)
{
HttpCookie byeCookie = new HttpCookie("thisuserlogin");
byeCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(byeCookie);
// Update Client
Response.Redirect(Request.RawUrl);
}
You should use a tool like Fiddler on the client side to capture all of the data going back and forth. This will help you see that your cookie should be set with a date in the past (and missing from the next request too).
As for your textbox output, you're listing the cookie you created expire time and the expire time of the request cookie, which doesn't have one. If you were to look at the response cookie instead, you should see the date being set. Also, the call to Response.Cookies.Set is unnecessary. Response.Cookies.Add should be all you need.

Categories

Resources