快速护照(node.js)错误处理

时间:2021-11-21 12:31:05

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在认证失败时做了什么。我有以下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?

在我看到'Error >一些err'控制台打印输出之后,没有发生任何其他事情。我认为它应该继续使用错误参数的下一条路径,但它似乎并没有这样做。这是怎么呢

3 个解决方案

#1


138  

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

战略执行与passport协同工作。验证两个身份验证请求,并处理成功/失败。

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. 在获取用户信息时发生内部错误(比如数据库连接没有);这个错误将被传递:next(err);这将由Express处理并生成HTTP 500响应;
  3. 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 false as 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);
  4. 所提供的凭证无效(没有用户使用提供的电子邮件地址,或密码不匹配);在这种情况下,您不会生成错误,但是您将一个false作为user对象传递:next(null, false);这将触发failureRedirect(如果您不定义一个,将生成一个HTTP 401未授权的响应);
  5. Everything checks out, you have a valid user object, so you pass it along: next(null, user); this will trigger the successRedirect;
  6. 一切都检出,你有一个有效的用户对象,所以你传递它:next(null, user);这将触发成功重定向;

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 failureFlash and installed 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并安装了connector -flash中间件,则提供的消息将存储在会话中,并且可以很容易地访问,例如,可以在模板中使用。

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

编辑:也可以自己完全处理身份验证过程的结果(而不是护照发送重定向或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);
});

#2


16  

What Christian was saying was you need to add the function

克里斯汀说的是你需要添加函数

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/

#3


2  

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

你需要添加req。登录(函数(err){ });并在回调函数中进行成功重定向

#1


138  

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

战略执行与passport协同工作。验证两个身份验证请求,并处理成功/失败。

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. 在获取用户信息时发生内部错误(比如数据库连接没有);这个错误将被传递:next(err);这将由Express处理并生成HTTP 500响应;
  3. 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 false as 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);
  4. 所提供的凭证无效(没有用户使用提供的电子邮件地址,或密码不匹配);在这种情况下,您不会生成错误,但是您将一个false作为user对象传递:next(null, false);这将触发failureRedirect(如果您不定义一个,将生成一个HTTP 401未授权的响应);
  5. Everything checks out, you have a valid user object, so you pass it along: next(null, user); this will trigger the successRedirect;
  6. 一切都检出,你有一个有效的用户对象,所以你传递它:next(null, user);这将触发成功重定向;

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 failureFlash and installed 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并安装了connector -flash中间件,则提供的消息将存储在会话中,并且可以很容易地访问,例如,可以在模板中使用。

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

编辑:也可以自己完全处理身份验证过程的结果(而不是护照发送重定向或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);
});

#2


16  

What Christian was saying was you need to add the function

克里斯汀说的是你需要添加函数

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/

#3


2  

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

你需要添加req。登录(函数(err){ });并在回调函数中进行成功重定向