Cannot get `cookieSession` working with `maxAge`

蓝咒 提交于 2019-12-24 07:25:16

问题


** SOLVED **

I've been struggling with this one for a bit. Lots of similar posts out there, but none of the proposed solutions are working for me.

I'm using Express and Passport with cookie sessions. When I pass just the secret to cookieSession everything works fine:

app.use(express.cookieParser('MySecret'));
app.use(express.cookieSession('MySecret'));
app.use(passport.initialize());
app.use(passport.session());

But the default cookie is session-based, and so it clears when you close your browser. I need a time-limited cookie. So I tried using the supposedly supported options:

app.use(express.cookieParser('MySecret'));
app.use(express.cookieSession({
  secret: 'MySecret',
  cookie: {
    maxAge: 365 * 24 * 60 * 60 * 1000
  }
}));
app.use(passport.initialize());
app.use(passport.session());

And it stops working. Seemingly the cookie is set in my browser and looks good, but there's no req.user, and subsequent requests are not authenticated.

I tried using maxage instead of maxAge to no avail. I can switch to the same config, but using express.session() instead of express.cookieSession() and it does work, but the session is lost when the server is restarted.

Any help?

edit: I'm on Express 3.20.2 btw


回答1:


This was user error. I'm not sure where I got the syntax for passing just the secret as a string to cookieSession() but that's invalid. It gets ignored, and actually falls back to using req.secret which is defined by the cookieParser('MySecret') call in the first place.

So that's why it was working with the original code. I still think this is a wtf moment though, because the second syntax should still work, but it doesn't. It boils down to this snippet in the cookieSession module:

if (!options.secret && req.secret) {
  req.session = req.signedCookies[key] || {};
  req.session.cookie = cookie;
} else {
  // TODO: refactor
  var rawCookie = req.cookies[key];
  if (rawCookie) {
    var unsigned = cookieParser.signedCookie(rawCookie, secret);
    if (unsigned) {
      var original = unsigned;
      req.session = cookieParser.JSONCookie(unsigned) || {};
      req.session.cookie = cookie;
    }
  }
}

So when you do pass a secret in the options for cookieSession it falls into the else block, and ends up setting a different cookie? I don't know, but it seems like a bug. If I'm using the same secret for both cookieParser and cookieSession it should be good. But anyway...

========

tl;dr it needs to be this:

app.use(express.cookieParser('MySecret'));
app.use(express.cookieSession({
  cookie: {
    maxAge: 30 * 24 * 60 * 60 * 1000
  }
}));


来源:https://stackoverflow.com/questions/30109331/cannot-get-cookiesession-working-with-maxage

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