【问题标题】:Node js passport local authentication is keep on loadingNode js护照本地身份验证继续加载
【发布时间】:2020-08-08 09:21:41
【问题描述】:

我正在使用节点 js(express 和 mysql)创建一个应用程序,尝试使用本地护照进行身份验证。当我点击登录时,一切运行正常,但在比较凭据成功重定向后不起作用(继续加载)。但如果凭据不匹配,则失败重定向工作正常没有任何错误

怎么了?在哪里?任何人都可以帮忙找出答案吗?请...

我的登录路径:

router.post('/login', (req, res, next) => { 
       console.log('post login.');          //never logged, why?
    passport.authenticate('local', {
      successRedirect: '/admin/dashboard',
      failureRedirect: '/login',
      failureFlash: true
    })(req, res, next);
  });

护照配置:

const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');

// Load User model
const User = require('../config/db').User;

module.exports = function(passport) {
  passport.use(
    new LocalStrategy({usernameField: 'email',  passwordField: 'password' }, (username, password, done) => {
      // Match user
      User.findOne({where: {email: username}}).then(user => {

        console.log(user.name);        //logged user name.

        if (!user) {

          return done(null, false, { message: 'That email is not registered' });
        }

        // Match password
        const isMatched = bcrypt.compareSync(password, user.password);

          if (isMatched) {
              console.log('password matched.');         //logged when password matched.
            return done(null, user);
          } else { console.log('password not matched.');    //logged when password not matched.
            return done(null, false, { error_msg: 'Password incorrect' });
          } 
      });
    })
  );

  passport.serializeUser(function(user, done) {
      console.log('serialized: ', user.id);       //logged when credentials matched.
    return done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.findByPk(id, function(err, user) {
        console.log('deserialized');

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

};

【问题讨论】:

  • 您查看过passportjs.org/docs 的文档吗?您在中间件中声明您的护照身份验证,而不是文档指定的方式。
  • 是的!我看过文档,但无法弄清楚。这就是为什么我遵循了一个教程但它没有用。

标签: mysql node.js express passport.js passport-local


【解决方案1】:

经过几个小时的谷歌搜索,我找到了解决方案,这里的问题在于 deserializeUser 方法。 我只是在 deserializeUser 中更改了一点代码,因为:passport 无法将用户反序列化出会话

它对我来说效果很好,我希望它对像我这样有问题的人也有用。

passport.deserializeUser(function(user, done) {
      return done(null, user);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-17
    • 2016-10-19
    • 2020-01-30
    • 2016-10-29
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多