PassportJS Custom Authenticate Callback Not Called

Update: An error below has been committed. I marked the first answer as β€œcorrect”, although the commit was brought to my attention in one of my comments

I was hoping to use a custom callback to handle both successes and failures for logging into Passport to authenticate a local strategy , but it looks like it only called for success.

Here is a snippet of what I'm talking about:

passport.use(new LocalStrategy( {usernameField: 'email', passwordField: 'password'}, function(email, password, done) { if(canLogin) done(null, user); else done({message: "This is an error message" }, false, { message: "Some Info" }); } )); app.post('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { // Only called if err is not set }); 

Any idea why this could be so? I was impressed that the callback would be called so that I could handle the errors myself.

+6
source share
1 answer

If you want to propagate an authentication failure (username and password mismatch), you should not generate an error, but set user to false and skip the reason:

 passport.use(new LocalStrategy( {usernameField: 'email', passwordField: 'password'}, function(email, password, done) { if (canLogin) done(null, user); else done(null, false, { message: 'Invalid login credentials' }); } )); ... app.post('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (user === false) { // handle login error ... } else { // handle successful login ... } })(req, res, next); }); 

err reserved for exceptions that occur during the authentication process, for example, if you receive DB errors, etc. But although Passport docs suggest that these errors will be passed to the passport.authenticate callback, they don't seem to (for whatever reason, it doesn't work for you).

+10
source

Source: https://habr.com/ru/post/958812/


All Articles