Search code examples
c#asp.net-mvcasp.net-mvc-4cookiesmachinekey

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?


Solution

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