尽管重新保存,NodeJS cookie 过期

NodeJS cookie expiration despite resave

是否可以为快速会话 cookie 设置一个 maxAge,以及一个用户可以重新保存 cookie 的 maxAge?例如我有以下设置:

app.use(session({
    secret: process.env.SECRET,
    saveUninitialized: false,
    resave: true,
    store: mongoDBStore,
    cookie: {
        maxAge: 12 * 60 * 60 * 1000
    }
}));

这样,用户有 12 小时的时间来刷新他的会话。但如果我没记错的话,他可以无休止地刷新他的会话。那么是否可以在例如 7 天后强制重新登录?

express-session should assist you in doing this automatically. Check out the rolling property.默认设置为false,这就是你想要的。

如果您绝对肯定必须让一个会话在特定时间过期,那么当您第一次创建一个会话时,您可以设置该过期时间,然后当它过去时您可以销毁该会话。像这个中间件(伪代码)这样​​的东西可能会成功。把它放在 use 快速会话中间件之后。这是 3_600_000 毫秒,一小时,持续时间。

app.use ( (req, res, next) => {
    const now = Date.now()
    if (!req.session.expiresAt) req.session.expiresAt = now + 3_600_000
    if (now >= req.session.expiresAt) {
      req.session.unset = 'destroy'
      next(createError(403, 'your session has expired. Please log in again.'))
    } else {
      next()
    }
} )

这应该会在当前请求完成后删除会话。即使它不删除浏览器 cookie,会话 ID 在下一次请求时也不会有效。

您需要 http-errors package 才能 createError()