【问题标题】:Safety of setting browser cookies from Express从 Express 设置浏览器 cookie 的安全性
【发布时间】:2021-09-05 15:19:40
【问题描述】:

最近部署了我的一个站点,我想知道这个允许 Heroku 上的 Express 服务器为我的 Netlify React 应用程序设置浏览器 cookie 的解决方案是否安全。我在其他地方的一个解释不清的 SO 答案中找到了它。

                                User.create(req.body)
                                .then(userNew => {
                                    res
                                        .cookie(
                                            "usertoken",
                                            jwt.sign({ _id: userNew._id }, process.env.JWT_KEY),
                                            {
                                                secure: true,
                                                sameSite: "none",
                                                httpOnly: false,
                                            }
                                        )
                                        .json({
                                            msg: "User registration success!",
                                            user: {
                                                _id: userNew._id,
                                                userName: userNew.userName,
                                                email: userNew.email,
                                                favs: userNew.favs,
                                            }
                                        });
                                })
                                .catch(err => res.status(400).json(err));

httpOnly、secure 和 sameSite 选项是我关心的。我过去只在开发中将 httpOnly 设置为“true”,没有任何问题,但这个解决方案在生产中对我有用。谢谢!

【问题讨论】:

    标签: express cookies jwt mern production


    【解决方案1】:
    • httpOnly 设置为true 以防止客户端访问cookie
    • 确保使用 expiresIn 选项为 JWT 设置到期时间。
    • 在 cookie 选项中设置 maxAge 与 JWT 到期时相同。
    • 您可以使用NODE_ENV 环境变量跟踪您是否在生产中。您可以以一种在生产和开发过程中不会不断更改代码的方式设置代码。

    这是我通常使用 cookie 和 JWT 的方式

      const isProd = process.env.NODE_ENV === 'production';
    
      res.cookie(
        'usertoken',
        jwt.sign({ _id: userNew._id }, process.env.JWT_KEY, { expiresIn: '1d' }),
        {
          secure: isProd,
          sameSite: isProd ? 'none' : 'lax',
          httpOnly: true,
          maxAge: 24 * 60 * 60 * 1000,
        }
      );
    

    【讨论】:

      猜你喜欢
      • 2019-08-02
      • 2021-02-14
      • 2014-05-07
      • 2014-08-10
      • 2020-06-06
      • 2015-04-18
      • 1970-01-01
      • 2018-10-26
      相关资源
      最近更新 更多