浏览器在重定向后不会从带有www的域发送cookie

问题描述 投票:1回答:1

我的网站有一个登台版本beta.example.com。我最近使用以下设置添加了cookie身份验证:

response.cookie(tokenName, token, {
  httpOnly: true,
  expires: new Date(Date.now() + (tokenExpirationSec * 1000))
})

在暂存身份验证中有效。

当我将代码部署到生产环境时,已成功设置cookie(通过Set-Cookie标头),但未在服务器端请求中将其发送到服务器。因此,当我刷新时,登录状态将消失,但会保留在客户端请求中。

值得注意的是,从example.comwww.example.com有301重定向。另外,host标头在生产中也为www.example.com

我最终如下设置cookie时通过添加domain参数解决了该问题:

response.cookie(tokenName, token, {
  httpOnly: true,
  expires: new Date(Date.now() + (tokenExpirationSec * 1000)),
  domain: '.example.com'
})

但是我不完全了解问题的根源。根据MDN

域指定允许主机接收cookie。如果未指定,则默认为当前文档位置的主机,不包括子域。如果指定了域,则总是包含子域。

因此,当我在未显式设置beta.example.com的情况下使用domain进行登台时,根据MDN隐式domain将为example.com,并且将排除beta.example.com。但是身份验证确实可以在分阶段工作!

但是我在生产www.example.com时有相同的情况,为什么它在生产中不起作用?

这是执行重定向的nginx配置:

server {
    listen       80 default_server;

    server_name beta.example.com;

    location / {
        include proxy_pass.inc;
    }
}

server {
    listen       80 default_server;

    server_name www.example.com;

    location / {
        include proxy_pass.inc;
    }
}

server {
    listen       80;
    server_name  example.com;
    return       301 https://www.example.com$request_uri;
}
authentication nginx redirect cookies http-status-code-301
1个回答
2
投票

我相信您误解了MDN documentation

如果未指定,则默认为当前文档位置的主机,不包括子域

表示如果您在beta.example.com上,则Domain将被设置为值beta.example.com。这将排除来自其他子域的cookie。

如果要在所有子域上使用cookie,则必须显式设置Domain

© www.soinside.com 2019 - 2024. All rights reserved.