首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在子域和域之间共享cookie?

如何在子域和域之间共享cookie?
EN

Stack Overflow用户
提问于 2018-03-05 07:53:52
回答 5查看 0关注 0票数 0

我有两个问题。 据我所知,如果我在cookie中指定域名为.mydomain.com(带有前导点),那么所有子域名都可以共享一个cookie。

subdomain.mydomain.com可以访问在mydomain.com(不含www子域)中创建的cookie吗?

如果在subdomain.mydomain.com中创建了cookie,mydomain.com(不含www子域)可以访问cookie吗?

EN

回答 5

Stack Overflow用户

发布于 2018-03-05 13:23:48

2个域mydomain.comsubdomain.mydomain.com只能在Set-Cookie头中明确指定域的情况下共享Cookie。 否则,cookie的范围仅限于请求主机。 (这被称为“仅限主机cookie”。)

例如,如果从subdomain.mydomain.com:

代码语言:javascript
复制
Set-Cookie: name=value

然后,就不会将cookie发送给mydomain.com但是,如果使用以下内容,则在这两个域上都可以使用它:

代码语言:javascript
复制
Set-Cookie: name=value; domain=mydomain.com

RFC 2109,没有前导点的域意味着不能在子域上使用它,而只有一个前导点(.mydomain.com)允许跨子域使用。

然而,现代浏览器尊重更新的规范。RFC 6265,并将忽略任何前导点,这意味着您可以在子域和顶级域上使用cookie。

总之,如果像上面的第二个例子一样设置了一个cookie,那么mydomain.com,它可以通过subdomain.mydomain.com,反之亦然。

另见:

票数 0
EN

Stack Overflow用户

发布于 2018-03-05 14:35:11

我不确定“cmackley”的答案是否显示了整个画面。我读到的是:

代码语言:javascript
复制
   Unless the cookie's attributes indicate otherwise, the cookie is
   returned only to the origin server (and not, for example, to any
   subdomains), and it expires at the end of the current session (as
   defined by the user agent).  User agents ignore unrecognized cookie
   attributes (but not the entire cookie).

还有

代码语言:javascript
复制
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.

票数 0
EN

Stack Overflow用户

发布于 2018-03-05 14:54:39

下面是一个使用DOM Cookie API的示例(https://developer.mozilla.org/en-US/docs/web/api/document/cookie),这样我们就可以自己看行为了。

如果我们执行以下JavaScript:

document.cookie=“key=value”

它似乎与执行:

document.cookie=“key=value;Domain=mydomain.com”

Cookie密钥仅在域mydomain.com上可用。

现在,如果在mydomain.com上执行以下JavaScript:

document.cookie=“key=value;Domain=.mydomain.com”

Cookie密钥可用于mydomain.com以及subdomain.mydomain.com。

最后,如果要在subdomain.mydomain.com上执行以下操作:

document.cookie=“key=value;Domain=.mydomain.com”

Cookie密钥是否可用于subdomain.mydomain.com? 我有点惊讶,这是允许的; 我曾假设,如果某个子域能够在父域上设置cookie,那将是一种安全违规行为。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100004197

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档