首页 > 解决方案 > Cookies and SameSite + Secure - ExpressJS

问题描述

The following warning is being shown in the console, even though I have the following settings on my express application. Has anyone seen this error before? My search brought me to https://github.com/expressjs/express/issues/3095

I am also using 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.

When doing a request using Insomia (Postman) I see the following

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

标签: javascriptnode.jsexpresscookies

解决方案


文档链接: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:添加了商店定义。

推荐阅读