我有以下代码:
// Setup express middleware
app.configure(function () {
app.use('/css', express.static(__dirname + '/public/css'));
app.use('/js', express.static(__dirname + '/public/js'));
app.use('/img', express.static(__dirname + '/public/img'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(cookieParser);
app.use(express.bodyParser());
app.use(express.cookieSession({
cookie: {
maxAge: 86400000
, signed: true
}
}));
app.use(express.session({
store: new RedisStore({host: "localhost", pass: "--", client: redis_client}),
secret: '--'
}));
app.use(express.csrf());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
app.get('/', function(req, res) {
if (req.user) {
res.redirect('/home');
} else {
res.redirect('/login');
}
});
app.post('/login',
passport.authenticate('local'),
function(req, res) {
console.log('login: ' + JSON.stringify(req.session));
req.session.cookie.expires = false;
req.session.cookie.maxAge = false;
console.log('after: ' + JSON.stringify(req.session));
res.redirect('/home');
}
);
app.get('/login', function(req,res) {
app.render('login', { welcome_msg: "TRR NANA", csrf_token: req.session._csrf}, function (err, html) {
if (err) {
logger.warn(err);
return;
}
res.send(html);
});
});
app.get('/home', ensureAuthenticated, function(req, res){
console.log('home:' + JSON.stringify(req.session));
app.render('home', { user: req.user}, function (err, html) {
if (err) {
logger.warn(err);
return;
}
res.send(html);
});
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
}
控制台中的输出是:
login: {"_csrf":"44CcIZ3kL2hkOpECrGnNF-GD","passport":{"user":18},"cookie":{"originalMaxAge":86400000,"expires":"2013-09-02T22:00:17.936Z","httpOnly":true,"path":"/"}}
after: {"_csrf":"44CcIZ3kL2hkOpECrGnNF-GD","passport":{"user":18},"cookie":{"originalMaxAge":false,"expires":false,"httpOnly":true,"path":"/"}}
home:{"_csrf":"44CcIZ3kL2hkOpECrGnNF-GD","passport":{"user":18},"cookie":{"originalMaxAge":86400000,"expires":"2013-09-02T22:00:17.949Z","httpOnly":true,"path":"/"}}
所以问题是:为什么重定向后cookie的到期时间和maxAge会有所不同?
你可能会问为什么我在使用express maxAge 8640000时将maxAge和expiration设置为false,答案是现在登录路由中的代码仅用于测试,我希望默认情况下cookie在一天内到期并且如果用户选中一个复选框,则cookie将在浏览器会话结束时到期。
但是,设置cookie的maxAge和expiration都不会改变浏览器中的cookie过期时间。