我有两个问题。我理解,如果我在cookie中指定域为.mydomain.com
(带前导点),那么所有子域都可以共享一个cookie。
subdomain.mydomain.com
是否可以访问在mydomain.com
中创建的cookie(没有www
子域)?
如果在subdomain.mydomain.com
中创建,mydomain.com
(没有www
子域)是否可以访问cookie?
只有在set-cookie
标头中显式命名域时,mydomain.com
和subdomain.mydomain.com
两个域才能共享cookie。否则,cookie的作用域将限于请求主机。(这被称为“仅有主机的cookie”。看看什么是仅有主机的cookie?)
例如,如果您从subdomain.mydomain.com
发送了以下标头,则不会为对mydomain.com
的请求发送cookie:
Set-Cookie: name=value
但是,如果您使用以下内容,则它将在两个域上都可用:
Set-Cookie: name=value; domain=mydomain.com
将为mydomain.com的任何子域发送此cookie,包括嵌套的子域,如subsub.subdomain.mydomain.com
。
在RFC 2109中,没有前导点的域意味着它不能在子域上使用,只有前导点(.mydomain.com
)才允许它跨多个子域使用(但不能跨顶级域,所以您所问的在旧规范中是不可能的)。
然而,所有现代浏览器都尊重较新的规范RFC6265,并且将忽略任何前导点,这意味着您可以在子域和顶级域上使用cookie。
总之,如果您在mydomain.com
中设置了一个类似上面第二个示例的cookie,则subdomain.mydomain.com
可以访问它,反之亦然。这也可以用于允许sub1.mydomain.com
和sub2.mydomain.com
共享cookie。
另见:
我不确定@CMBuckley答案是否显示了全部情况。我读到的是:
除非cookie的属性另有指示,否则cookie只返回到原始服务器(例如,不返回到任何子域),并且它在当前会话结束时过期(由用户代理定义)。用户代理忽略无法识别的Cookie。
RFC 6265
也
8.6. Weak Integrity
Cookies do not provide integrity guarantees for sibling domains (and
their subdomains). For example, consider foo.example.com and
bar.example.com. The foo.example.com server can set a cookie with a
Domain attribute of "example.com" (possibly overwriting an existing
"example.com" cookie set by bar.example.com), and the user agent will
include that cookie in HTTP requests to bar.example.com. In the
worst case, bar.example.com will be unable to distinguish this cookie
from a cookie it set itself. The foo.example.com server might be
able to leverage this ability to mount an attack against
bar.example.com.
对我来说,这意味着您可以保护cookie不被子域/域读取,但不能阻止将cookie写入其他域。因此有人可能会通过控制同一浏览器访问的另一个子域来重写您的站点cookie。这可能不是什么大问题。
@cmbuckley/为那些像我一样在他的答案中错过了的人提供的令人敬畏的cookies测试站点;值得向上滚动并向上投票/: