Nice programing

Express Passport (node.js) 오류 처리

nicepro 2020. 11. 19. 21:58
반응형

Express Passport (node.js) 오류 처리


이 스택 교환을 통해 노드에서 오류 처리가 어떻게 작동해야하는지 살펴 보았지만 인증에 실패했을 때 여권이 무엇을하는지 잘 모르겠습니다. 다음 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);
    });
  }
));

'오류> 일부 오류'콘솔 출력이 표시되면 아무 일도 일어나지 않습니다. 오류 매개 변수를 사용하여 다음 경로에서 계속되어야한다고 생각하지만 그렇게하지 않는 것 같습니다. 무슨 일이야?


전략 구현은 passport.authenticate요청을 인증하고 성공 / 실패를 처리하기 위해 함께 작동합니다 .

이 경로 (이메일 주소와 암호가 전달됨)를 사용하고 있다고 가정합니다.

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

그러면 전략에서 코드가 호출되며 세 가지 조건 중 하나가 발생할 수 있습니다.

  1. 사용자 정보를 가져 오는 중에 내부 오류가 발생했습니다 (예 : 데이터베이스 연결이 끊어졌습니다). 이 오류는 다음에서 전달됩니다. next(err); 이것은 Express에서 처리하고 HTTP 500 응답을 생성합니다.
  2. 제공된 자격 증명이 잘못되었습니다 (제공된 전자 메일 주소를 가진 사용자가 없거나 암호가 일치하지 않습니다). 이 경우 오류를 생성하지 않지만 a false를 사용자 개체로 전달 합니다. next(null, false); 이것은 failureRedirect(당신이 정의하지 않으면 HTTP 401 Unauthorized 응답이 생성 될 것입니다);
  3. 모든 것이 확인되고 유효한 사용자 객체가 있으므로 다음과 같이 전달합니다. next(null, user); 이것은 트리거합니다 successRedirect;

유효하지 않은 인증 (내부 오류가 아님)의 경우 콜백과 함께 추가 메시지를 전달할 수 있습니다.

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

connect-flash 미들웨어를 사용 failureFlash 하고 설치 경우 제공된 메시지는 세션에 저장되며 예를 들어 템플릿에서 사용할 수 있도록 쉽게 액세스 할 수 있습니다.

편집 : 인증 프로세스의 결과를 직접 처리 할 수도 있습니다 (패스포트가 리디렉션 또는 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);
});

Christian이 말한 것은 기능을 추가해야한다는 것입니다.

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

따라서 전체 경로는 다음과 같습니다.

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

출처 : http://passportjs.org/guide/login/


req.logIn(function (err) { });콜백 함수 내에서 성공 리디렉션 을 추가 하고 수행해야합니다.

참고 URL : https://stackoverflow.com/questions/15711127/express-passport-node-js-error-handling

반응형