提问者:小点点

Nodejs和PassportJS:在Passport之后重定向中间件。如果身份验证失败,则不调用Authenticate


我没有登录页面,但我有一个登录表单,出现在每个页面上。我想重定向用户回到相同的页面,无论身份验证是否成功(使用适当的闪存消息)

请执行以下代码:

app.post('/login', validateLogin, passport.authenticate('local-login'), function(req, res) {

    var redirectUrl = '/'; 

    if(req.body.to.length > 0){
        redirectUrl = req.body.to;  
    }

    console.log("THIS IS ONLY CALLED IF passport.authenticate() IS SUCCESSFUL");
    res.redirect(redirectUrl);
});

我只看到上面的最后一个中间件在认证通过的情况下被调用。如果失败,passport似乎会以get请求的形式将我重定向到/login。在我的应用程序中,这个页面不存在。

如果我在passport authenticate函数中传递了一个附加的options对象作为参数,则会起作用:

app.post('/login', validateLogin, passport.authenticate('local-login', {

successRedirect : '/', // redirect to the secure profile section
    failureRedirect : '/signup', // redirect back to the signup page. THIS IS JUST FOR TESTING TO SEE IF THE REDIRECT ON FAIL WORKS.
    failureFlash : true, // allow flash messages

}


));

但是在这样做的过程中,我失去了选择将用户重定向到何处的能力。如果身份验证失败,passport似乎会控制用户被重定向到的位置。我该怎么解决这个问题?还是一个窃听器?如果身份验证失败,passport authenticate必须是链中的最后一个中间件吗?

这是我的本地策略函数调用:

//LOCAL 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


    console.log("IN PASSPORT");

   if(email.length == 0 || password.length == 0){

       console.log("FIELDS ARE EMPTY"); 
      return done(null, false, req.flash('loginMessage', 'Fill in all values.'));

   }

    // 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);
        console.log("db err");
        }
        // if no user is found, return the message
        if (!user){
            console.log("not user");
            return done(null, false, req.flash('loginMessage', 'Incorrect details.')); // 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)){
            console.log("invalid pw");
            return done(null, false, req.flash('loginMessage', 'Incorrect details.')); // create the loginMessage and save it to session as flashdata
        }    
        // all is well, return successful user
        console.log("All OK");
        return done(null, user);
    });

}));

共3个答案

匿名用户

您可以使用上一段所述的自定义身份验证回调http://passportjs.org/guide/authenticate/。

app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    // Redirect if it fails
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      // Redirect if it succeeds
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

匿名用户

我遇到了同样的问题,重定向调用,在成功的Facebook认证之后

。。。没有得到荣誉。

基于'local'passportJS策略--从@ploutch's的回答中可以很好地提醒一下这一点…我意识到让它工作的关键似乎就在这个电话里:

req.logIn(user, function(err) {
 ...
}

在Facebook上,这个路由设置对我很有效:

app.get(
        '/auth/facebook/callback',

        passport.authenticate
        (
            'facebook', 
            { failureRedirect: '/fbFailed' }
        ),

        function(req, res) 
        {
            var user = myGetUserFunc(); // Get user object from DB or etc

            req.logIn(user, function(err) {

              if (err) { 
                req.flash('error', 'SOMETHING BAD HAPPEND');
                return res.redirect('/login');
              }

              req.session.user = user;

              // Redirect if it succeeds
              req.flash('success', 'Fb Auth successful');
              return res.redirect('/user/home');
            });      
        }
); 

匿名用户

完整答案,包括:

只需在中间件中创建一个值:

var loginRequired = function(req, res, next) {
    if ( req.isAuthenticated() ) {
        next();
        return
    }
    // Redirect here if logged in successfully
    req.session.redirectTo = req.path;
    res.redirect('/login')
}

然后在您的登录文章中:

router.post('/login', function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if ( err ) {
            next(err);
            return
        }
        // User does not exist
        if ( ! user ) {
            req.flash('error', 'Invalid email or password');
            res.redirect('/login');
            return
        }
        req.logIn(user, function(err) {
            // Invalid password
            if ( err ) {
                req.flash('error', 'Invalid email or password');
                next(err);
                return
            }
            res.redirect(req.session.redirectTo || '/orders');
            return
        });
    })(req, res, next);
});