使用节点8.11.3,Express 4.16.3,Express-Session 1.15.6
我使用有效期限很短的cookie创建会话:
var expiryDate = new Date(Date.now() + 1 * 60 * 1000) // 1 minute
app.use(session({
store: new MongoStore({ url: config.gmi.db.url }),
secret: 'sdfsdfsdfsdf',
resave: true,
saveUninitialized: true,
cookie: {
expires: expiryDate //TODO secure cookies when we go to HTTPS
}
}));
我应该在路由上得到401,但是当我注销然后重新登录时,好像我正在接管过期的会话:
LOGIN SESSION>>>>> {"cookie":{"originalMaxAge":-1181398,"expires":"2018-07-10T17:43:19.339Z","httpOnly":true,"path":"/"},"username":"derek@sdf.com"}
POST /login 200 48578.580 ms - 2
{"cookie":{"originalMaxAge":-1234394,"expires":"2018-07-10T17:43:19.339Z","httpOnly":true,"path":"/"}}
GET /tenants 401 3064.476 ms - 12
这是我的路线中间件:
var auth = function(req, res, next) {
console.log(JSON.stringify(req.session));
if (req.session && req.session.username)
return next();
else
return res.sendStatus(401);
};
和我的注销例程:
app.get('/logout', function (req, res) {
req.session.destroy();
res.send("logout success!");
});
我的登录名只需设置用户名:
req.session.username = req.body.username;
console.log("LOGIN SESSION>>>>>", JSON.stringify(req.session));
它不是应该使用新的到期时间和originalMaxAge创建新的会话吗?我的浏览器上也没有cookie。
答案 0 :(得分:0)
我需要重设最大年龄和有效期,因为这些总是与用户相关联。
所以我的登录名是这样的
//find user in DB
//make sure password is good
if (req.session.cookie && req.session.cookie.originalMaxAge < 0) {
var hour = 1 * 60 * 1000;
req.session.cookie.expires = new Date(Date.now() + hour)
req.session.cookie.maxAge = hour
}
req.session.username = req.body.username;
console.log("LOGIN SESSION>>>>>", JSON.stringify(req.session));
有关此的一些信息: https://github.com/expressjs/session#cookiemaxage-1