修改会话不保存
Posted
技术标签:
【中文标题】修改会话不保存【英文标题】:Modifying session is not saving 【发布时间】:2018-08-25 22:33:48 【问题描述】:我使用的是 nodejs 8.9.3 和 express 4.15.5。
我正在做的是尝试在登录时将用户信息保存到req
。身份验证成功后,我重新指定用户变量。然后一旦完成,当我访问 '/dashboard'
时,用户信息不会被存储。
我的尝试
使用不同的组合将快速会话项目(如 saveUninitialized、重新保存和滚动)更改为 true/false。 登录中间件中的req.session.save() 将登录响应从res.send(stuff)
更改为 res.redirect('/dashboard')
试图将用户存储在req.session.user
而不是req.user
我在尝试让它工作时完全没有运气。
app.js
...
app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: false ));
app.use(cookieParser());
app.use(session(
secret: 'javascript',
saveUninitialized: true,
resave: false,
rolling: false,
cookie:
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
secure: process.env.NODE_env === 'production', // currently false as NODE_env is development atm
));
...
// Load routes
require('./routes/auth.js')(app);
auth.js
let userPre =
dn: '',
userPrincipalName: '',
sAMAccountName: '',
displayName: '',
pwdLastSet: '',
memberOf: [],
isAuthenticated: false
;
module.exports = (app) =>
let user = function(req, res, next)
req.user = userPre;
next();
;
app.use(user);
app.get('/', (req, res) =>
res.render('login', title: 'Login');
);
app.post('/api/login', async(req, res) =>
await ad.user(req.body.userName).authenticate(req.body.password)
.then(async(authResponse) =>
if (authResponse === true)
return await ad.user(req.body.userName).get();
else if (authResponse === false)
res.send('failed');
return false;
)
.then(userProfile =>
if (!userProfile)
return false;
else
req.user =
dn: userProfile.dn,
userPrincipalName: userProfile.userPrincipalName,
sAMAccountName: userProfile.sAMAccountName,
displayName: userProfile.displayName,
pwdLastSet: userProfile.pwdLastSet,
memberOf: [],
isAuthenticated: true
;
userProfile['groups'].forEach(group => req.user.memberOf.push(group.cn));
if (req.user.memberOf.filter(obj => obj === 'Cat'))
// authentication is successful and now I want to redirect to dashboard with req.user still being set.
// Tried req.session.save() here as well.
console.log(req.user); // Data has been set
res.redirect('/dashboard');
else
res.send('success') // ignore
)
.catch(err => console.log(err));
);
...
app.get('/dashboard', (req, res) =>
console.log(req.user); // all variables are still ''.
res.render('dashboard', title: 'Dashboard')
);
...
;
【问题讨论】:
【参考方案1】:您几乎就在那里,您所要做的就是将用户存储在req.session.user
而不是req.user
。
req.session.user =
dn: userProfile.dn,
userPrincipalName: userProfile.userPrincipalName,
sAMAccountName: userProfile.sAMAccountName,
displayName: userProfile.displayName,
pwdLastSet: userProfile.pwdLastSet,
memberOf: [],
isAuthenticated: true
;
【讨论】:
哇。从现在开始就赚了很多。我用你的方法修改它来工作。非常感谢。以上是关于修改会话不保存的主要内容,如果未能解决你的问题,请参考以下文章