Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

javascript - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));

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
});
  • Edit 1: Fixed issue pointed out by CaptainAdmin
  • Edit 2: Added store definition.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...