node.js - 如何在 Cookie 上指定 SameSite 和 Secure(使用 axios/React/Node Express)
问题描述
我有这个聊天应用程序已经工作了一段时间,但突然之间它在客户端给了我这个问题:
Because a cookie's SameSite attribute was not set or is invalid, it defaults to SameSite=Lax,
which prevents the cookie from being set in a cross-site context. This behavior protects
user data from accidentally leaking to third parties and cross-site request forgery.
Resolve this issue by updating the attributes of the cookie:
Specify SameSite=None and Secure if the cookie is intended to be set in cross-site contexts.
Note that only cookies sent over HTTPS may use the Secure attribute.
我在我的 React 客户端上使用这样的 axios:
axios.defaults.withCredentials = true
axios.post('https://easytalkchatappv2.herokuapp.com/signin', {
username: username,
password: password
}).then(res => {
console.log(res.data)
})
我正在使用 JWT 设置 cookie,方法是在 /signin 的 post 请求中的 Nodejs Express 服务器中执行此操作:
const user = {id: resp.insertedId}
const accessToken = await jwt.sign(user, process.env.ACCESS_TOKEN_SECRET)
res.cookie('token', accessToken)
我也在使用 cookie-parser。如何将这些 SameSite 和 Secure 属性添加到 cookie?
解决方案
您应该能够将 'secure' 和 'sameSite' 属性传递给 res.cookie 方法;像下面的 x 被替换为您想要使用的值:
res.cookie('token', accessToken, { sameSite: x, secure: x })
如 Express 文档中所示: https ://expressjs.com/en/api.html#res.cookie
推荐阅读
- angular - Ionic Cordova ios 在滚动时闪烁
- c++ - 有没有办法在 OpenCV 中本地解决二次规划问题?
- django - 在 django 启动期间设置全局设置
- php - WordPress 插件开发:如何将文件上传到默认的“上传”目录?
- google-sheets - 如何在 Google 表格的过滤器中使用 REGEXMATCH 和 SPLIT?
- java - 如何在 java 中调整动画 gif 文件的大小?
- c# - 在 C# 中打开 Excel 文件并调用加载项命令
- csv - 为什么这段代码不将给定的数字分成 .csv 文件中的不同列?
- amazon-web-services - AWS CloudFront 和 ELB:请求未到达后端
- python - 如何在没有最终分隔符的情况下组合字符串