Deleting Cookies (or Managing Cookie Domains) in ASP.NET

I just spent a good few hours wrestling with writing authentication cookies in ASP.NET across different sub-domains. I've done enough SSO installations to know how it should work & what the hiccups are. Today I was reminded of a good lesson. I was writing a Cookie out via Response.Cookies.Add() in 2 sites. The problem was the second site was not overwriting the value from the first. So I tried to delete the cookie. I set the expiration to the past, I removed it from the collection, I tried using Klaus Hartl's jQuery plugin. Nothing was deleting this cookie.

Then I realized what I was doing wrong -- I was setting the Domain in the first instance but NOT in the second. ASP.NET was using different domains in the cookie. What I learned was that the more general, top-level domain was taking priority over the default domain.

Another issue to consider is the fact that Visual Studio 2008 and IIS will read the Cookie values different depending upon their Domain. Let's say we set 3 cookies (with the same name, but different values) with 3 different domains: the top-level domain, a subdomain and the default domain.


HttpCookie tldCookie = new HttpCookie("Name", "TLD Value")
Domain = "topdomain.com"

HttpCookie subDomainCookie = new HttpCookie("Name", "Subdomain Value")
Domain = "subdomain.topdomain.com"

HttpCookie defaultCookie = new HttpCookie("Name", "Default (No-Domain) Value");


If we read the "Name" cookie on another page using the ASP.NET Development Server -- what should the value be?

HttpCookie cookie = Request.Cookies["Name"];
if (cookie == null) return;

...this will write Default (No-Domain) Value as the value while running locally. If you run the same page on subdomain.topdomain.com it will return TLD Value.

Top-Level Domains will take precedence over other domains. Moreover, the subdomain cookie will be there (if you use the WebDev toolbar + View Cookies); however, it is not readable within the Response.Cookies collection.

No comments: