Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get cookie only from second level domain?

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.

like image 651
徐明明 Avatar asked Aug 25 '10 14:08

徐明明


1 Answers

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).

like image 195
Gumbo Avatar answered Sep 23 '22 08:09

Gumbo