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

时间:2020-04-07 15:23:11

标签: authentication nginx redirect cookies http-status-code-301

我的网站有一个登台版本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'
})

但是我不完全理解问题的根源。根据{{​​3}}

域指定允许主机接收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;
}

1 个答案:

答案 0 :(得分:3)

我相信您误解了MDN documentation

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

意思是如果您在beta.example.com上,那么Domain将被设置为值beta.example.com。这将从其他子域中排除该Cookie。

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

相关问题