Cookies 和 SameSite + Secure - ExpressJS

Eri*_*c E 14 javascript cookies node.js express

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

我也在使用快递:4.17.1

let COOKIE_OPTIONS = { httpOnly: true, sameSite: 'None', secure: true };
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)

使用 Insomia (Postman) 执行请求时,我看到以下内容

access_token=someToken; 
Path=/; 
HttpOnly; 
Secure; 
SameSite=None
Run Code Online (Sandbox Code Playgroud)

小智 12

您可以在不使用任何节点包的情况下设置这些选项。仅使用 Express 如下所示:

app.get('/', (req,res)=>{
    //.....Other Code
    res.cookie('cookieName', 'cookieValue', { sameSite: 'none', secure: true})
    //.....Other Code
})
Run Code Online (Sandbox Code Playgroud)


Ada*_*cha 8

Documentation Link: https://www.npmjs.com/package/express-session#cookiesamesite

The below code will solve your issue. This is also recommended going forward.

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));
Run Code Online (Sandbox Code Playgroud)

In your case, set sameSite to 'none'

In case you are wondering what is store? I am using my database as storage for all the cookies. It's not relevant to the question asked by OP. Just added as pointed by @klevis in the comment. Here's the code:

const KnexSessionStore = require('connect-session-knex')(session);
const store = new KnexSessionStore({
  tablename: 'session',
  knex: kx,
  createtable: false
});
Run Code Online (Sandbox Code Playgroud)
  • Edit 1: Fixed issue pointed out by CaptainAdmin
  • Edit 2: Added store definition.


小智 2

据我所知,这是关于 chrome 未来新实现的警告

Cookie 上的 SameSite 选项:从 Chrome 80 开始,未指定 SameSite 属性的 Cookie 将被视为 SameSite=Lax,并具有附加行为,即它们仍将包含在 POST 请求中,以简化现有站点的转换。

任何进一步信息: https: //www.chromium.org/updates/same-site

如果您想测试您的网页,本文将介绍如何设置 Chrome 标记以进行测试。如果您的页面停止工作,您必须检查所有请求并查看“http://”到“https://”的更新或检查第三方 cookie