在带有 express-session 的 NodeJS 中使用安全 cookie 时,会话不会持久化

3 session-cookies node.js express express-session

我正在使用 NodeJS + express + express-session 从应用程序的任何地方保留用户 ID。

在第一条路线上,我的会话已定义

userProfileRoutes.route('/authentication').post((req, res) => {
  req.session.userID = 10; //example
  console.log(req.session)
}
Run Code Online (Sandbox Code Playgroud)

的结果console.log是:

Session {
  cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: true },
  userID: 10 } // this is the right value
Run Code Online (Sandbox Code Playgroud)

但是,从不同的路线,我看不到价值:

userProfileRoutes.route('/edit').get(function (req, res) {
  console.log('After the nav edit route');
  console.log(req.session);
}
Run Code Online (Sandbox Code Playgroud)

这打印

Session {
  cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: true }
} // ID VARIABLE DISAPEARS HERE
Run Code Online (Sandbox Code Playgroud)

我正在express-session使用这些参数进行配置:

app.use(session({
  secret: 'secret',
  proxy: true,
  resave: false,
  saveUninitialized: true,
  withCredentials: true,
  cookie: { secure: true },
  store: new MongoStore({ mongooseConnection: db })
}));
Run Code Online (Sandbox Code Playgroud)

为什么我的用户 ID 在请求之间和所有路由上都没有保留?

luc*_*aro 5

您正在设置cookie: {secure: true}但尝试使用 HTTP 访问您的服务器。

来自express-session 文档

cookie.secure

请注意将此设置为 true 时要小心,因为如果浏览器没有 HTTPS 连接,兼容客户端将来不会将 cookie 发送回服务器。

请注意,secure: true 是推荐选项。但是,它需要启用 https 的网站,即安全 cookie 需要 HTTPS。如果设置了安全,并且您通过 HTTP 访问您的站点,则不会设置 cookie。

确保您使用 HTTPS(始终在生产中!)或设置cookie.secure为 false(也许,仅用于开发!)

cookie 中的安全标志

安全标志是应用程序服务器在 HTTP 响应中向用户发送新 cookie 时可以设置的一个选项。安全标志的目的是防止 cookie 因以明文形式传输 cookie 而被未授权方观察到。

为了实现这一目标,支持安全标志的浏览器只会在请求进入 HTTPS 页面时发送带有安全标志的 cookie。换句话说,浏览器不会通过未加密的 HTTP 请求发送设置了安全标志的 cookie。通过设置安全标志,浏览器将阻止通过未加密通道传输 cookie。

来自https://www.owasp.org/index.php/SecureFlag

快速会话中的 Cookie

按照惯例,express-session使用 cookie 来存储会话 ID和服务器端存储(在您的情况下为 mongoDB)来存储会话数据。如果浏览器因为找不到有效的 cookie 而没有发送您的会话 ID,您的服务器将假定没有会话,并在每次请求的新会话中保存用户 ID。

当您到达时,/authentication它将在新会话中保存 ID。当您尝试读入不同的请求时,会话 ID 已更改并且您在 中没有任何值userID