我有一个Express应用,其中的会话很麻烦。
代码通常可以正常使用,成功登录后,应将用户定向到“仪表板”页面(如果未请求特定的URL)。
login.js将req.session.user设置为用户信息的对象。
要检查是否授权了任何路由,我有一个中间件(authuser.js)用于检查req.session.user
问题是该测试(显然是随机的)失败了。这是控制台的(已编辑)日志,您可以在其中看到login.js报告req.session.user,然后是authuser.js在req.session.user上的测试失败:
Login success - session: Session {
cookie:
{ path: '/',
_expires: 2019-08-24T13:30:16.023Z,
originalMaxAge: 604800000,
httpOnly: true },
requested_url: '/dashboard',
__lastAccess: 1566048616023,
user:
{ username: 'me',
display_name: 'Jeff',
role: 'admin',
groups: null,
set_password: true,
organisation: 'jeff',
organisation_id: '1',
maxDiskSpace: '2048000000',
default_module: 'default',} }
Login -redirecting to /dashboard
Auth user: No req.session.user /dashboard
POST /login 302 131.560 ms - 64
GET /dashboard 302 1.167 ms - 56
GET /login 200 20.086 ms - 1203
app.js:
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var fileStoreOptions = {};
var sess = {
store: new FileStore(fileStoreOptions),
secret: 'Fuzz-whib-49',
resave: true,
saveUninitialized: false,
cookie: {
maxAge: 7 * 24 * 3600 * 1000 // 7 days
}
}
app.use(session(sess));
login.js:
router.post('/', function(req, res, next) {
auth.login( req )
.then( user => {
req.session.user = user;
var next_route = req.query.next || req.session.requested_url || '/dashboard';
delete req.session.requested_url;
res.redirect(next_route)
})
.catch( function( error) {
...
dashboard.js:
router.get('/', authUser, function(req, res, next) {
console.log('Dashboard: Session id: ' + req.session.id);
console.log('Dashboard - user: ' + req.session.user.username);
var mod = loadAppModule(req.session.user);
var title = mod.title;
res.render("dashboard", {
module: mod,
user: req.session.user,
});
});
authuser.js中间件:
module.exports = function(req, res, next) {
if(req.session.user) {
next();
} else {
console.log('Auth user: No req.session.user ' + req.originalUrl)
req.session.requested_url = req.originalUrl;
res.redirect('/login')
}
}
logout.js
router.post('/', authUser, function(req, res, next) {
console.log('Logout ' + req.session.user.username);
req.session.destroy(function(){
res.redirect('/');
});
});
有什么作用?
答案 0 :(得分:0)
问题似乎出在会话文件存储中。尝试读取authuser.js中的"req.session.user = user;"
时,login.js中的呼叫req.session.user
尚未与光盘同步吗?
通过使用cookie-session而不是session-file-store,问题就消失了...
app.js:
var cookieSession = require('cookie-session')
...
app.use(cookieSession({
name: name,
keys: [key],
// Cookie Options
maxAge: 7 * 24 * 3600 * 1000 // 7 days
}));