【问题标题】:Passport-local never authenticating with correct credentialsPassport-local 从不使用正确的凭据进行身份验证
【发布时间】:2016-11-16 23:42:42
【问题描述】:

我正在尝试使用passport-local 将一些身份验证和密码哈希烘焙到一个小型网络应用程序中。我相信我已经正确设置了它,但是即使凭据 110% 正确,我也会通过失败重定向再次登录。

护照文档对调试错误的描述非常简单,任何人都可以分享一些关于此失败重定向的可能原因,或提供继续调试的解决方案吗?

护照配置

passport.use(new LocalStrategy({
  usernameField: 'email',
  passwordField: 'password'
},
  function(username, password, cb) {
     UserSchema.findByUsername(username, function(err, user) {
      if (err) { return cb(err); }
      if (!user) { return cb(null, false); }
      if (user.password != password) { return cb(null, false); }
      return cb(null, user);
    });
  }));

登录路径

router.post('/login',
  passport.authenticate('local', {
    failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

Schema 和 findByUsername 函数

const UserSchema = mongoose.Schema ({
  firstName: {
    type: String,
    index: true
  },
  lastName: {
    type: String,
    index: true
  },
  email: {
    type: String,
    index: true
  },
  password: {
    type: String,
    index: true
  },
  homeAirport: {
    type: String,
    index: true
  }
})

UserSchema.plugin(passportLocalMongoose)

// Adding this function to find by username
exports.findByUsername = function(username, cb) {
  process.nextTick(function() {
    for (var i = 0, len = records.length; i < len; i++) {
      var record = records[i];
      if (record.username === username) {
        return cb(null, record);
      }
    }
    return cb(null, null);
  });
}

// Export it to the app
module.exports = mongoose.model('user', UserSchema)

【问题讨论】:

  • 作为调试步骤,将用户返回函数替换为返回文字用户对象的函数。
  • 另外,我在这方面有点菜鸟,但在我尝试的一个小项目中,我使用了 passportLocalMongoose,它将用户名、密码、盐等添加到我的用户模型以及找到的方法这里github.com/saintedlama/…

标签: javascript node.js mongodb passport.js passport-local


【解决方案1】:

取自 Passport 文档:

重定向通常在验证请求后发出。

我的猜测是因为你只有一个{failureRedirect: '/login' }
你总是被重定向到那里。尝试添加:

app.post('/login',
  passport.authenticate('local', { successRedirect: '/',
                                   failureRedirect: '/login' }));

所以在这种情况下,您有一个 successRedirect 和一个 failureRedirect

或者您也可以在身份验证后删除重定向,而是像这样重定向用户:

app.post('/login',
  passport.authenticate('local'),
  function(req, res) {
    console.log('Successfully logged in');
    res.redirect('/users/' + req.user.username);
  });

让我知道这是否有效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2021-10-15
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多