javascript - Cookies 和 SameSite + Secure - ExpressJS

标签 javascript node.js express cookies

控制台中显示以下警告,即使我在我的 express 应用程序中进行了以下设置。有没有人见过这个错误?我的搜索将我带到了 https://github.com/expressjs/express/issues/3095

我也在用 express : 4.17.1

let COOKIE_OPTIONS = { httpOnly: true, sameSite: 'None', secure: true };
A cookie associated with a cross-site resource at http://MYURL.URL was set
without the `SameSite` attribute. A future release of Chrome will only deliver 
cookies with cross-site requests if they are set with `SameSite=None` and 
`Secure`. You can review cookies in developer tools under 
Application>Storage>Cookies and see more details at 
https://www.chromestatus.com/feature/5088147346030592 and 
https://www.chromestatus.com/feature/5633521622188032.

当使用 Insomia (Postman) 发出请求时,我看到以下内容

access_token=someToken; 
Path=/; 
HttpOnly; 
Secure; 
SameSite=None

最佳答案

文档链接:https://www.npmjs.com/package/express-session#cookiesamesite

下面的代码将解决您的问题。也建议继续这样做。

const express = require('express');
const session = require('express-session');
const app = express();

const sessionConfig = {
  secret: 'MYSECRET',
  name: 'appName',
  resave: false,
  saveUninitialized: false,
  store: store,
  cookie : {
    sameSite: 'strict', // THIS is the config you are looing for.
  }
};

if (process.env.NODE_ENV === 'production') {
  app.set('trust proxy', 1); // trust first proxy
  sessionConfig.cookie.secure = true; // serve secure cookies
}

app.use(session(sessionConfig));

在您的情况下,将 sameSite 设置为 'none'

如果您想知道什么是store?我正在使用我的数据库作为所有 cookie 的存储。这与 OP 提出的问题无关。刚刚按照@klevis 在评论中指出的那样添加。这是代码:

const KnexSessionStore = require('connect-session-knex')(session);
const store = new KnexSessionStore({
  tablename: 'session',
  knex: kx,
  createtable: false
});
  • 编辑 1:修复了 CaptainAdmin
  • 指出的问题
  • 编辑 2:添加商店定义。

关于javascript - Cookies 和 SameSite + Secure - ExpressJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58228871/

相关文章:

javascript - 如何使用 Express 设置日志记录级别?

javascript - 为什么我导出的函数不是函数?

Javascript - 非事件用户注销

javascript - req.body 在分配给变量后更改值

node.js - 实时数据库消息传递

node.js - 获取渲染名称jade

node.js - Node js - 快速发送 pdf 作为响应下载

javascript - 在其他 div 位置插入 div

javascript - 将 URL 查询参数转换为对象 - 保留类型?

javascript - "Not a constructor",但类型检查出来