未调用PassportJS自定义身份验证回调 [英] PassportJS Custom Authenticate Callback Not Called

查看:83
本文介绍了未调用PassportJS自定义身份验证回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:以下错误已由一次提交修复.我已将第一个答案标记为正确",尽管该提交在其评论中引起了我的注意

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

我希望通过自定义回调在Passport的验证本地策略中处理登录成功与失败的情况,但看起来只有成功才被调用.

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.

推荐答案

如果要传播身份验证失败(用户名/密码不匹配),则不应该生成错误,而是将user设置为false并传递原因:

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

err是保留给身份验证过程中发生的异常的,例如,如果您遇到DB错误等.但是,尽管Passport文档建议这些错误将传递给passport.authenticate回调,但它们似乎并没有(这就是它对您不起作用的原因).

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).

这篇关于未调用PassportJS自定义身份验证回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆