PassportJS Custom Authenticate Callback Not Called

北城余情 提交于 2020-01-01 05:19:11

问题


Update: The below error was fixed by a commit. I've marked the first answer as 'correct', though the commit was brought to my attention in one of its comments

I was hoping to utilize the custom callback to handle both successes and failures for logins in Passport's authenticate local strategy, but it looks like it's only called on 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 might be the case? I was under the impression the callback would be called so I can handle errors myself.


回答1:


If you want to propagate an authentication failure (username/password mismatch), you shouldn't generate an error, but set the user to false and pass a reason along:

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);
});

The err is reserved for exceptions that occur during the authentication process, for instance if you get DB-errors and such. But although the Passport docs suggest that those errors will be passed to the passport.authenticate callback, they don't seem to (which is the reason why it's not working for you).



来源:https://stackoverflow.com/questions/20206583/passportjs-custom-authenticate-callback-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!