简体   繁体   English

Passport.js成功认证完全不调用

[英]Passport.js successful authentication not calling at all

Here is My code : 这是我的代码:

passport.use(new localStrategy(
    function(username, password, done) {
        User.findOne({
            username: username
        }, function(err, user) {
            if (err) throw err;
            if (!user) {
                console.log("Unknown User");
                return done(null, false, {
                    message: "Unknown User"
                })
            }
            if (!user.validPassword(password)) {
                console.log("Incorrect password.", password);
                return done(null, false, {
                    message: 'Incorrect password.'
                });
            }

            console.log("User Is detected");
            return done(null, user, {
                message: "User Is detected"

            })

        });
    }
));


router.post('/login',
    passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/users/login',
        failureFlash: true,
        successFlash: 'Welcome!'
    }),
    function(req, res) { // this function not called
        console.log(req)
    });

everything works perfectly , but success function not calling and i want to have this message : "welcome"+req.body.username after logged in . 一切正常,但成功函数未调用,我希望登录后显示以下消息: "welcome"+req.body.username

Any Advice ? 有什么建议吗? thx 谢谢

From the documentation of passport.authenticate() : passport.authenticate()文档中

the redirect options override the default behavior 重定向选项将覆盖默认行为

In your example, because you set the successRedirect option, the next function in the middleware chain will not be invoked upon successful authentication. 在您的示例中,因为您设置了successRedirect选项,所以成功认证后将不会调用中间件链中的下一个函数。

If you want to your function to be invoked before redirecting to '/' , then you should: 如果要在重定向到'/'之前调用函数,则应该:

router.post('/login',
    passport.authenticate('local', {
        failureRedirect: '/users/login',
        failureFlash: true
    }),
    function(req, res) {
        // This should show up in your logs:
        console.log('Welcome ' + req.body.username);

        // You can also use a flash to consume after redirect:
        // (provided that you use connect-flash in your app)
        req.flash('info', 'Welcome ' + req.body.username);

        res.redirect('/');
    }
);

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

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