Updating cookie session in express not registering with browser

会有一股神秘感。 提交于 2019-11-30 21:29:06

Express-session supports a rolling cookie expiration date. Unfortunately, it was only recently documented.

Use the "rolling" option for your session. This "forces a cookie set on every response" and "resets the expiration date." You want to set rolling to true.

Also pay attention to the "resave" option. That "forces session to be saved even when unmodified..." You'll likely want to set that option to true as well. Note that even though the default value is true for this option, you should set the value explicitly. Relying on the default for this option, rather than setting it explicitly, is now deprecated.

Try something like:

app.use( session( { secret: 'keyboard cat',
                    cookie: { maxAge: 60000 },
                    rolling: true,
                    resave: true, 
                    saveUninitialized: false
                  }
         )
);

Here's the documentation. Look under "Options" and "options.resave": https://github.com/expressjs/session .

After some digging it turns out Express does not support this sort of rolling, and is left as an exercise for the programmer to implement.

It would help if the browsers expirary was reliably readable to express, so you could bump the session only when it's close to expirary, but I use this as a workaround (inefficient) until I figure something smarter out:

check_auth = function(req, res, next) {
  console.log(req.isAuthenticated());
  if (req.isAuthenticated()) {
    if (req.session.roll) {
      req.session.roll = 0;
    } else {
      req.session.roll = 1;
    }
    return next();
  }
  return res.redirect('/login');
};

Where roll could be anything, the point being the session is changed (on every auth-checked request*).

*) which also means it's wildly inefficient, but it will do for now.

One alternative could be to lookup the TTL of the session id. This would have to be checked in a way like: if ttl < 10% * maxAge (as defined by the app), as the TTL is actually correctly updated on every request, it's just that Set-Cookie isn't sent. As such, say the user stays within the 90% of maxAge, his browser-cookie will eventually expire, so even that approach is not sufficient. It could be a good middleground though.

I'll leave the question unaccepted, to encourage others to weigh in with better solutions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!