【问题标题】:Not able to set cookie from the express app hosted on Heroku无法从 Heroku 上托管的 express 应用设置 cookie
【发布时间】:2020-09-18 05:06:24
【问题描述】:

我在 Heroku 中托管了前端和后端。

  • 前端 - xxxxxx.herokuapp.com(反应应用)
  • 后端 - yyyyyy.herokuapp.com(快递)

我正在尝试实施 Google 身份验证。从 Google OAuth2 获取令牌后,我尝试通过 express 应用在 cookie 中设置id_token 和用户详细信息。

下面是我在后端的一段代码,

authRouter.get('/token', async (req, res) => {
    try {
        const result = await getToken(String(req.query.code))
        const { id_token, userId, name, exp } = result;
        const cookieConfig = { domain: '.herokuapp.com', expires: new Date(exp * 1000), secure: true }
        res.status(201)
            .cookie('auth_token', id_token, {
                httpOnly: true,
                ...cookieConfig

            })
            .cookie('user_id', userId, cookieConfig)
            .cookie('user_name', name, cookieConfig)
            .send("Login succeeded")
    } catch (err) {
        res.status(401).send("Login failed");
    }
});

它在我的本地对我来说非常有效,但它在 heroku 上不起作用。

这些是我已经尝试过的域 - .herokuapp.com herokuapp.com。另外,我尝试了没有指定域字段本身。

我可以在响应标头上看到 Set-Cookie 详细信息,但 /token 端点失败且未返回任何状态代码,并且我看不到应用程序选项卡上设置的 cookie。

请看下面的图片,

我在这里看不到任何状态代码,但它说它失败了。 这些是我可以看到的 cookie 信息,但如果我通过应用程序选项卡检查,则它不可用。

我在这里缺少什么?有人可以帮我吗?

【问题讨论】:

  • 有什么解决办法吗?
  • 后来意识到 herokuapp.com 包含在 Mozilla 基金会的公共后缀列表中,因此它会阻止您在 herokuapp.com 或 *.herokuapp.com 上设置 cookie
  • 好的,除了herokuapp,还有其他的网络主机可以使用吗?这基本上是为了测试cookies
  • 不确定其他托管平台是否有能力管理 cookie,但我建议使用自定义域,它会解决问题。

标签: node.js express heroku cookies setcookie


【解决方案1】:

您应该尝试安全: secure: req.secure || req.headers['x-forwarded-proto'] === 'https'

【讨论】:

    【解决方案2】:

    你是对的,这在技术上应该可行。

    除非它确实有效,否则这可能会导致大规模的安全漏洞,因为任何能够创建 Heroku 子域的人都可以为所有其他子域生成会话 cookie。

    这不仅是 Heroku 的安全问题,还包括任何其他允许您拥有子域的服务。

    这就是为什么从那时起创建并维护了一个域列表以列出不应在子域之间共享 cookie 的公共域。此列表通常由浏览器使用。

    您可以想象,域 heroku.com 是此列表的一部分。

    如果您想了解更多信息,此列表称为 Mozilla 基金会的Public Suffix List

    【讨论】:

      猜你喜欢
      • 2021-03-30
      • 2019-05-17
      • 2021-06-10
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      相关资源
      最近更新 更多