views:

26

answers:

2

There are two domains: a.example.com example.com

example.com is the parent domain of a.example.com. Now both a.example.com and example.com may write a cookie named test_cookie. Now we have a page of a.example.com which will use javascript to read value of cookie test_cookie. Is there a way that only read the cookie set in the domain of a.example.com rather than example.com?


Maybe my question was a little unclear,

the goal i want to achieve is: 1. i want to write a function named readCookie to read the cookie with name test_cookie which: a. when there is a cookie: test_cookie under domain example.com and NO cookie test_cookie under domain a.example.com, readCookie returns null b. when there is a cookie: test_cookie under domain example.com AND ALSO a cookie test_cookie under domain a.example.com, readCookie returns the cookie value under domain a.example.com c. when there NO cookie: test_cookie under exampler.com, but there is a cookie test_cookie under domain a.example.com, readCookie returns the cookie value under domain a.example.com.

+1  A: 

It's not possible to limit a cookie to example.com-only by setting the domain parameter. However, in most browsers, a cookie will default to example.com-only if no domain is supplied. Unfortunately in IE it defaults to allowing subdomains access to the cookie.

This is why you put your main site at www.example.com and not just example.com. With a site on the main domain example.com you cannot reliably keep your cookies separate.

bobince
+3  A: 

That depends on how the cookie was defined, especially if the Domain attribute is specified what values it has (see RFC 2965 – User Agent Role):

  • if Domain attribute is missing, the user agent assumes the current host; otherwise
  • if Domain attribute is set, its value must start with a . like .example.com (if not, e.g. example.com, it will get changed by the user agent to .example.com).

Now the domain of a cookies must domain-match the a domain to be send within the request. And that is the case:

  • if either the domains are identical (in case the Domain parameter was missing), or
  • if the value specified in the Domain attribute must be a suffix of the domain.

That means:

 effective domain | example.com | a.example.com | foo.example.com | bar.a.example.com
------------------+-------------+---------------+-----------------+-------------------
      example.com |      ✓      |      ✗        |        ✗        |         ✗
    a.example.com |      ✗      |      ✓        |        ✗        |         ✗
     .example.com |      ✓      |      ✓        |        ✓        |         ✓
   .a.example.com |      ✗      |      ✓        |        ✗        |         ✓

So if you want a cookie to only be valid for a.example.com, you either omit the Domain attribute or you specify the Domain attribute with .a.example.com (that will make the cookie valid for a.example.com as well as its subdomains).

Gumbo