问题
** 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