简体   繁体   English

PassportJs 在身份验证后不重定向

[英]PassportJs not redirecting after authentication

I'm having some trouble with using Passport for authentication.我在使用 Passport 进行身份验证时遇到了一些问题。 I've defined my signup strategy as follows:我已经定义了我的注册策略如下:

    passport.use('local_signup', new localStrategy({
  usernameField: 'username',
  passwordField:'password',
  passReqToCallback: true
},function(req,username, password,done){
User.findOne({username: username},function(err,user){
  if(err){
    console.log(err);
  } else{
    if(user){
      console.log("user exists.") 
    }
    else{
      const newUser = new User();
      newUser.email = req.body.email;
      newUser.password =req.body.password;
      newUser.username = req.body.user_name;
      newUser.first_name = req.body.first_name;
      newUser.last_name = req.body.last_name;
      newUser.save(function(err){
        if(err){
          console.log(err);
        }else{
          console.log('success');
        }
      })
    }
  }

})
})
)

I've then called this strategy in my register route然后我在我的注册路线中调用了这个策略

app.post('/register', passport.authenticate('local_signup', {
        successRedirect : '/drinks',
        failureRedirect : '/register',
        failureFlash : true
    }));

If the authentication was successful it should trigger the drinks route如果认证成功,它应该触发饮料路线

  app.get('/drinks',function(req,res){
    if(req.isAuthenticated()){
      res.render('start');
    } else {
      res.redirect('/login')
  }

}) 

successRedirect isn't redirecting to the desired page. successRedirect 不会重定向到所需的页面。 It remains stuck on the register route.它仍然停留在注册路线上。 The populated users however are showing up on my database so at least my strategy is working.然而,填充的用户显示在我的数据库中,所以至少我的策略是有效的。 I don't know how to debug this.我不知道如何调试这个。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks谢谢

You are not making use of done() .您没有使用done() From what I understand, it is an exit point from the strategy code and letting the flow go to success or failure based on the params you pass in it.据我所知,它是策略代码的退出点,并根据您传入的参数让流程走向成功或失败。 It is a param in your callback in your strategy implementation code.它是策略实现代码中回调中的一个参数。 It is something internal to passport .这是护照内部的东西

Call it like this in case of success:如果成功,可以这样调用:

return done(null, newUser);

Call it like this in case of error:出错时这样调用:

done(err);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM