Share cookie between subdomain and domain

前端 未结 7 1792
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 13:58

I have two questions. I understand that if I specify the domain as .mydomain.com (with the leading dot) in the cookie that all subdomains can share a cookie.

7条回答
  •  忘了有多久
    2020-11-21 14:16

    Here is an example using the DOM cookie API (https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie), so we can see for ourselves the behavior.

    If we execute the following JavaScript:

    document.cookie = "key=value"

    It appears to be the same as executing:

    document.cookie = "key=value;domain=mydomain.com"

    The cookie key becomes available (only) on the domain mydomain.com.


    Now, if you execute the following JavaScript on mydomain.com:

    document.cookie = "key=value;domain=.mydomain.com"

    The cookie key becomes available to mydomain.com as well as subdomain.mydomain.com.


    Finally, if you were to try and execute the following on subdomain.mydomain.com:

    document.cookie = "key=value;domain=.mydomain.com"

    Does the cookie key become available to subdomain.mydomain.com? I was a bit surprised that this is allowed; I had assumed it would be a security violation for a subdomain to be able to set a cookie on a parent domain.

提交回复
热议问题