我无法让 Passport 对我的用户进行身份验证。由于某种原因,passport.authenticate 方法总是失败。我不明白的是,如果我在护照调用之前添加中间件,用户数据可以通过req.user
.
关于为什么 passport.authenticate 失败的任何想法?
app.get('/app'
// MY USER SHOWS UP HERE
, function(req, res, next) {
console.log("app.get('/app')", req.user);
next();
}
// DOESN'T MAKE IT PAST HERE
, passport.authenticate('local', { failureRedirect: '/login', failureFlash: true })
// NEVER MAKES IT HERE
, function(req, res) {
console.log('FTW!!!');
res.render('../../client/app/app')
}
);
验证码
passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' },
function(email, password, done) {
console.log("Authenticating user: ", email, password);
User.findOne({ email: email }, function (err, user) {
if (err) return done(err);
if (!user) return done(null, false, { message: 'Invalid Email' });
return user.authenticate(password, function(err, valid) {
if (err) return done(err);
if (!valid) return done(null, false, { message: 'Invalid Password' });
return done(null, user);
});
});
}
));
passport.serializeUser(function(user, done) {
console.log('Serializing: ', user);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log('Deserializing: ', id);
User.findById(id, function (err, user) {
done(err, user);
});
});
注册和重定向:在找到用户后注意 ['Missing Credentials'] 消息
// SIGN UP
Authenticating user: cacky23@acme.org.com foobar
User.authenticate(): Comparing... // user.authenticate()
Compare Complete... true // bcrypt compare
Serializing: { email: 'cacky23@acme.org.com',
password: '$2a$10$TJcvr4wtgs6DFaNnyQSLt.v5GLbt8PIi.oOlgqZpvghveKEPEcroW',
_id: 52160e247d0aa8e328000001,
__v: 0,
createdAt: Thu Aug 22 2013 07:12:04 GMT-0600 (MDT) }
POST /users 302 185ms - 64b
Deserializing: 52160e247d0aa8e328000001
Found User: { email: 'cacky23@acme.org.com',
password: '$2a$10$TJcvr4wtgs6DFaNnyQSLt.v5GLbt8PIi.oOlgqZpvghveKEPEcroW',
_id: 52160e247d0aa8e328000001,
__v: 0,
createdAt: Thu Aug 22 2013 07:12:04 GMT-0600 (MDT) }
// MY TEST MIDDLEWARE
app.get('/app') { email: 'cacky23@acme.org.com',
password: '$2a$10$TJcvr4wtgs6DFaNnyQSLt.v5GLbt8PIi.oOlgqZpvghveKEPEcroW',
_id: 52160e247d0aa8e328000001,
__v: 0,
createdAt: Thu Aug 22 2013 07:12:04 GMT-0600 (MDT) }
GET /app 302 6ms - 68b
Deserializing: 52160e247d0aa8e328000001
Found User: { email: 'cacky23@acme.org.com',
password: '$2a$10$TJcvr4wtgs6DFaNnyQSLt.v5GLbt8PIi.oOlgqZpvghveKEPEcroW',
_id: 52160e247d0aa8e328000001,
__v: 0,
createdAt: Thu Aug 22 2013 07:12:04 GMT-0600 (MDT) }
[ 'Missing credentials' ]
GET /login 200 85ms - 3.65kb