Node.js Passport不会调用下一个函数

我使用Node来构build一个应用程序,使用Passport.js来处理使用本地数据库的用户login。

所以我有下面的代码,当用户去/configuration文件被调用。 成功login后,用户被redirect到/ profile。 根据摩根,这发生了什么。

app.get('/profile', passport.authenticate('local-login', { session : false, failureRedirect : '/login' }), function(req, res) { console.log("testnow"); res.render('profile.ejs', { user : req.user // get the user out of session and pass to template }); }); 

我的本地login代码如下。

 passport.use('local-login', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : 'email', passwordField : 'password', passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, email, password, done) { // callback with email and password from our form // find a user whose email is the same as the forms email // we are checking to see if the user trying to login already exists User.findOne({ 'local.email' : email }, function(err, user) { // if there are any errors, return the error before anything else if (err) return done(err); // if no user is found, return the message if (!user) return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash // if the user is found but the password is wrong if (!user.validPassword(password)) return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata // all is well, return successful user console.log("testdone"); return done(null, user); }); })); 

在testing代​​码时,我login并redirect到configuration文件一秒钟。 控制台打印在我的本地login代码中的“testdone”,但不打印“testnow”,因为它是预期的。 意思是我的/ profile get方法中的第二个函数似乎从来没有被调用,即使是本地login正在调用下一个函数。

因此,从最终用户的立场来看,您login(在幕后,您将redirect到/剖面部分)和/ profile将您redirect到/ login。

任何想法如何解决这个问题,所以我/configuration文件get方法中的第二个函数实际上被调用?

非常感谢。 我也很乐意提供任何额外的信息来帮助解决这个问题。

passport.authenticate()是为了处理实际的authentication; 换句话说,就是取得login凭据并将其传递给策略。 如果它们已经被authentication,这并不意味着传递请求,这是你正在尝试使用它。

相反,你想使用像connect-ensure-login这样的东西来保护用户必须login的路由。

另请参阅此Passport示例项目 。