Express Passport (node.js) 错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15711127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:03:21  来源:igfitidea点击:

Express Passport (node.js) error handling

node.jsexpresspassport.js

提问by Omid Ahourai

I've looked at how error handling should work in node via this stack exchange, but I'm not sure what passport's doing when it fails authentication. I have the following LocalStrategy:

我已经通过此堆栈交换查看了错误处理在节点中的工作方式,但我不确定护照在身份验证失败时在做什么。我有以下本地策略:

passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' },
  function(email, password, next) {

    User.find({email: UemOrUnm}, function(err, user){
      if (err) { console.log('Error > some err'); return next(err); }
      if (!user) { console.log('Error > no user'); return next('Incorrect login or password'); } 

      if (password != user.password) {
        return next(Incorrect login or password);
      }
      return next(null, user);
    });
  }
));

After I see 'Error > some err' console printout, nothing else happens. I would think it should continue on the the next path with an error parameter, but it doesn't seem to do that. What's going on?

在我看到“错误 > 一些错误”控制台打印输出后,没有其他任何反应。我认为它应该在带有错误参数的下一条路径上继续,但它似乎并没有这样做。这是怎么回事?

回答by robertklep

The strategy-implementation works in conjunction with passport.authenticateto both authenticate a request, and handle success/failure.

策略实现与passport.authenticate验证请求和处理成功/失败一起工作。

Say you're using this route (which is passed an e-mail address and a password):

假设您正在使用此路由(通过电子邮件地址和密码):

app.post('/login', passport.authenticate('local', {
  successRedirect: '/loggedin',
  failureRedirect: '/login', // see text
  failureFlash: true // optional, see text as well
});

This will call the code in the strategy, where one of three conditions can happen:

这将调用策略中的代码,其中可能发生以下三种情况之一:

  1. An internal error occurred trying to fetch the users' information (say the database connection is gone); this error would be passed on: next(err); this will be handled by Express and generate an HTTP 500 response;
  2. The provided credentials are invalid (there is no user with the supplied e-mail address, or the password is a mismatch); in that case, you don't generate an error, but you pass a falseas the user object: next(null, false); this will trigger the failureRedirect(if you don't define one, a HTTP 401 Unauthorized response will be generated);
  3. Everything checks out, you have a valid user object, so you pass it along: next(null, user); this will trigger the successRedirect;
  1. 尝试获取用户信息时发生内部错误(假设数据库连接消失);这个错误将被传递:next(err); 这将由 Express 处理并生成 HTTP 500 响应;
  2. 提供的凭据无效(没有用户具有提供的电子邮件地址,或者密码不匹配);在这种情况下,你不产生一个错误,但你传递一个false为用户对象:next(null, false); 这将触发failureRedirect(如果您没有定义,将生成一个 HTTP 401 未经授权的响应);
  3. 一切检查出来,你有一个有效的用户对象,所以你把它传递:next(null, user); 这将触发successRedirect;

In case of an invalid authentication (but not an internal error), you can pass an extra message along with the callback:

如果身份验证无效(但不是内部错误),您可以随回调传递额外的消息:

next(null, false, { message : 'invalid e-mail address or password' });

If you have used failureFlashandinstalled the connect-flash middleware, the supplied message is stored in the session and can be accessed easily to, for example, be used in a template.

如果您已经使用failureFlash安装了 connect-flash 中间件,则提供的消息将存储在会话中,并且可以轻松访问,例如,在模板中使用。

EDIT:it's also possible to completely handle the result of the authentication process yourself (instead of Passport sending a redirect or 401):

编辑:也可以自己完全处理身份验证过程的结果(而不是 Passport 发送重定向或 401):

app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) {
      return next(err); // will generate a 500 error
    }
    // Generate a JSON response reflecting authentication status
    if (! user) {
      return res.send({ success : false, message : 'authentication failed' });
    }
    // ***********************************************************************
    // "Note that when using a custom callback, it becomes the application's
    // responsibility to establish a session (by calling req.login()) and send
    // a response."
    // Source: http://passportjs.org/docs
    // ***********************************************************************
    req.login(user, loginErr => {
      if (loginErr) {
        return next(loginErr);
      }
      return res.send({ success : true, message : 'authentication succeeded' });
    });      
  })(req, res, next);
});

回答by cpoole

What Christian was saying was you need to add the function

Christian 所说的是你需要添加函数

req.login(user, function(err){
  if(err){
    return next(err);
  }
  return res.send({success:true});
});

So the whole route would be:

所以整个路线将是:

app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) {
      return next(err); // will generate a 500 error
    }
    // Generate a JSON response reflecting authentication status
    if (! user) {
      return res.send(401,{ success : false, message : 'authentication failed' });
    }
    req.login(user, function(err){
      if(err){
        return next(err);
      }
      return res.send({ success : true, message : 'authentication succeeded' });        
    });
  })(req, res, next);
});

source: http://passportjs.org/guide/login/

来源:http: //passportjs.org/guide/login/

回答by Christian Nagorka

You need to add req.logIn(function (err) { });and do the success redirect inside the callback function

您需要req.logIn(function (err) { });在回调函数中添加并执行成功重定向