Passport js local strategy custom callback showing

2019-01-29 13:01发布

问题:

I am using Node.js,angularjs,express and passport. I have tried all options I can think of, but still no solution. Couldn't find a solution from other posts for this problem.

app.post('/login', function(req, res, next) {

console.log(req.body.Email);
console.log(req.body.Password);

passport.authenticate('local', function(err, user, info) {

    console.log(err,user,info);
...

In above req.body is showing correct in console but in passport authenticate it is showing null,false and info as missing credentials.

I have used the following for pass port

passport.use(new LocalStrategy({ usernameField: 'Email' }, (Email, Password, done) => {
console.log(Email, Password, done);
User.findOne({ Email: Email.toLowerCase() }, (err, user) => {
    console.log(err);
    if (err) { return done(err); }
    if (!user) {
        return done(null, false, { msg: `Email ${Email} not found.` });
    }
    user.ComparePassword(Password, (err, isMatch) => {
        if (err) { return done(err); }
        if (isMatch) {
            return done(null, user);
        }
        return done(null, false, { msg: 'Invalid email or password.' });
    });
});
}));


passport.serializeUser((user, done) => {
   // console.log(user, done);
    done(null, user.id);
});

passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
        done(err, user);
    });
});

I couldn't understand why the problem exist.

Does anybody know what I am missing here?!?!

Thanks!

回答1:

Use { usernameField: 'email' } not { usernameField: 'Email' } because you send req.body.email not req.body.Email



回答2:

Adding upto kaxi answer I have made to solve this error by adding password field in the passport local strategy as below

 passport.use(new LocalStrategy({ usernameField: 'Email',passwordField: 'Password'  }, (Email, Password, done) 

in place of

passport.use(new LocalStrategy({ usernameField: 'Email' }, (Email, Password, done)