我是express-session的新手。它的行为和我期望的不一样,我想知道是否有人能指出原因。这可能是一个基本的用户错误。
我正在开发一个应用程序,用于存储志愿者K-9搜索和救援队的培训信息。我正在尝试使用PassportJS验证登录。我正在通过Mongo Atlas存储数据。我现在只想看到它基本上能正常工作,以便进一步开发。
下面是我如何设置中间件:
router.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true
}))
(我不确定我是否误用了Passport,因此我也将展示我是如何构建Passport的):
router.use(passport.initialize())
router.use(passport.session())
authUser = async (username, password, done) => {
const returnedUser = await User.findOne({username: username}, (err, user) => {
if (err) {
return err
} else {
return user
}
})
.clone()
if (!returnedUser) {
return done(null, false)
} else if (returnedUser.password != password) {
return done(null, false)
} else {
return done(null, returnedUser)
}
}
passport.use(new LocalStrategy (authUser))
passport.serializeUser( (userObj, done) => {
done(null, userObj)
})
passport.deserializeUser((userObj, done) => {
done (null, userObj )
})
当我登录,并且console.log()
会话...
router.post('/signIn', passport.authenticate('local', {
// failureRedirect: 'http://localhost:3000/users/signIn'
failureMessage: 'failure'
}), (req, res) => {
console.log('req.session:', req.session)
res.send('finished')
})
......我在控制台中得到了预期的结果:
req.session: Session {
cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true },
passport: {
user: {
_id: new ObjectId("62e5505409d8b098030b70aa"),
username: 'cap1',
password: 'America',
firstName: 'Steve',
lastName: 'Rogers',
email: 'cap@notshield.org',
phoneNumber: 1234567890,
dateCreated: 2022-07-30T15:37:56.079Z,
k9s: [Array],
__v: 0
}
}
}
(我知道需要加密此密码,但在尝试理解密码时,我暂时将其保持可见。)
但是,当我测试它是否持续时...
router.post('/', async (req, res) => {
console.log(req.session)
//check all field on the front end
let postUser = new User({
"username": req.body.username,
// "password": await hasher(req.query.password, 10),
"password": req.body.password,
"firstName": req.body.firstName,
"lastName": req.body.lastName,
"email": req.body.email,
"phoneNumber": req.body.phoneNumber,
"dateCreated": new Date(),
//query must must be formatted like
//&k9s[]=spike&k9s[]=lucey
"k9s": req.query.k9s
})
postNew(postUser, res)
})
...会话在console.log()中不包含passport信息:
Session {
cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }
}
(我意识到,在实践中,需要登录会话来创建新用户是没有意义的。我只是尝试使用两个我知道有效的函数来测试它。)
为什么会话不保留http请求之间的Passport JS信息?
1条答案
按热度按时间rkue9o1l1#
这可能是因为您使用的passport版本的原因。我最近在从0.4.1迁移到0.6.0后遇到了类似的问题,这可能改变了登录/注销时会话持续的方式,以解决此漏洞:https://github.com/advisories/GHSA-v923-w3x8-wh69
如果将
keepSessionInfo: true
选项添加到authenticate
与logout
方法中,则其行为仍与0.4.1版相同.对于身份验证:
passport.authenticate("local", {keepSessionInfo: true})
注销:
passport.logout({keepSessionInfo: true}, (err) => {})
查看此GitHub问题:https://github.com/jaredhanson/passport/issues/949