【问题标题】:NodeJS cookie expiration despite resave尽管重新保存,NodeJS cookie 过期
【发布时间】:2021-05-18 11:47:58
【问题描述】:

是否可以为 express-session 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 天后强制重新登录?

【问题讨论】:

    标签: node.js express-session


    【解决方案1】:

    express-session 应该会帮助您自动执行此操作。查看rolling property. 默认设置为false,这就是你想要的。

    如果您绝对肯定会话必须在某个时间过期,那么当您第一次创建会话时,您可以设置该过期时间,然后在过期时您可以销毁会话。像这个中间件(伪代码)这样​​的东西可能会奏效。把它放在use express-session 中间件之后。这里是 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 在下一次请求时也将无效。

    createError() 需要 http-errors package

    【讨论】:

    • 会检查rolling属性,不过中间件也是个好主意!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 2015-09-03
    • 2017-08-14
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多