【问题标题】:Passport callback isn't called未调用 Passport 回调
【发布时间】:2017-08-10 13:06:50
【问题描述】:

我使用Passport lib 使用this tutorial(它的一部分)构建了一个应用程序。

注意,我不需要注册,只需要登录表单。

其中一个问题是我的 LocalStrategy 回调从未被调用。对于存储,我使用 mongo:

mongoose.connect(dbConfig.url, {
    useMongoClient: true
});

//dbConfig

module.exports = {
    'url' : 'mongodb://localhost/passport'
}

登录路径如下所示:

module.exports = function(app, passport) {
    app.get('/login', function(req, res) {
        res.render('login', {
            message: req.flash('loginMessage')
        });
    });

    app.post('/login', passport.authenticate('login', {
        successRedirect: '/', // redirect to the secure profile section
        failureRedirect: '/login', // redirect back to the signup page if there is an error
        failureFlash: true // allow flash messages
    }));
}

护照逻辑是:

module.exports = function(passport) {    
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    passport.use('login', new LocalStrategy({
        passReqToCallback: true 
    }, function(req, username, password, done) {
        console.log('start'); // never called

        User.findOne({
            'local.email': email
        }, function(err, user) {
            if (err) {
                return done(err);
            }

            if (!user) {
                return done(null, false, req.flash('loginMessage', 'No user found.'));
            }

            if (!user.validPassword(password)) {
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
            }

            return done(null, user);
        });
    }));
};

console.log('start'); 从未被调用,尽管 passport.authenticate('login' ...) 被调用。

可能是什么问题?

【问题讨论】:

    标签: javascript passport.js


    【解决方案1】:

    我终于修好了,一切正常。如果有人遇到同样的问题,我会在这里发布几个问题和解决方案。

    我的 app.post 中的 req.body 是空的,因为我没有添加正文解析器。修复它:

    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    

    用户名字段一直是空的,因为我将其命名为 email 并且护照需要 username。修正:

    new LocalStrategy({
            usernameField: 'email', // this parameter
            passReqToCallback: true
        }
    

    【讨论】:

      猜你喜欢
      • 2016-08-10
      • 2018-07-25
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2015-11-19
      • 2014-09-01
      相关资源
      最近更新 更多