最近部署了我的一个站点,我想知道这个允许 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”而没有问题,但是这个解决方案在生产中对我有用。谢谢!
答案 0 :(得分:1)
httpOnly
设置为 true
以防止客户端访问 cookieexpiresIn
选项为 JWT 设置过期时间。maxAge
。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,
}
);