【问题标题】:How to change passport to use email instead of username for authenticating?如何更改护照以使用电子邮件而不是用户名进行身份验证?
【发布时间】:2017-09-25 03:30:07
【问题描述】:

我想使用用户的电子邮件和密码登录。 但是在护照中你应该使用用户名。

我已经尝试了很多关于如何做到这一点的示例。但非工作。 真正的问题是应用程序想要将记录保存到数据库中。 虽然我已更改代码以查找电子邮件而不是用户名字段,但这是保存到数据库的最终记录:

'name': 'joseph',
'username' : 'example@gmail.com',
.
.

但我不希望将电子邮件另存为用户名。 当我在用户注册后用猫鼬更改它时,它会是正确的,但是当应用程序想要验证用户身份时,问题就会再次出现。

它将在数据库而不是电子邮件中查找用户名字段。因为用户将提供电子邮件作为用户名,所以登录将失败。

代码:

app.get("/register", function(req, res) {
   var newUser = new User({
    username :  req.body.username,
    email :  req.body.email,
    name: req.body.name
  });

  User.register(newUser, req.body.password, function(err, user) {
    if (err) {
      req.flash('error', "An error ocurred, please try again.");
      return res.redirect('back');
    } else {
      passport.authenticate("local")(req, res, function() {
        req.flash("success", "Welcome");
        res.redirect("/admin");
      });
    }
  });

});

此代码以我想要的方式注册用户,但问题在于登录:

router.post('/login', middleware.outLoggedIn, passport.authenticate("local", {
    successRedirect: "/admin",
    failureRedirect: "/login",
    failureFlash: "Invalid username or password",
    successFlash: "Welcome!"
}));

它总是失败,因为它会获取登录表单中提供的用户电子邮件,然后将其与数据库中的电子邮件进行比较。由于我已经用电子邮件和用户名保存了用户,它会将登录表单中提供的电子邮件与数据库中的用户名字段进行比较。并且失败了。

这是数据库中的用户:

{
    "_id" : ObjectId("5901cc5c0256ed17b4d61960"),
    "salt" : "---",
    "hash" : "---",
    "username" : "joseph320",
    "email" : "example@gmail.com",
    "name" : "joseph",
    "__v" : 0
}

(登录表格需要邮箱和密码)

我也这样做了:

passport.use(new localStrategy({
  usernameField: 'email'
}, User.authenticate()));

如果你能告诉我如何解决这个问题,我真的很感激。

【问题讨论】:

  • 不是一个完整的答案,但它可能会解决您的问题。我相信您的最后一个代码 sn-p 应该以 User.authenticate)); 结尾而不调用该函数。
  • 用它代替validPassword函数?
  • 没有。您的最后一行有User.authenticate(),它将立即调用该函数。我相信您只想要User.authenticate,这样您就可以将该功能传递给护照。如果您在问题中包含 User.authenticate 函数也会有所帮助。

标签: node.js passport.js


【解决方案1】:

您能否提供更多代码?某些上下文在这里很重要,例如您使用哪些 npm 模块来读取和写入数据库。

** 如果您使用的是passport-local-mongoose

您说您正在使用 mongoose,看起来您可能还在使用 passport-local-mongoose。如果是这种情况,您可以查看passport-local-mongoose 的选项。这还包括一个usernameField 选项,它指示您希望将“用户名”存储在哪里。其用法如下所示:

User.plugin(passportLocalMongoose, {usernameField: 'email'})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 2010-10-16
    • 2020-07-18
    • 2017-12-28
    相关资源
    最近更新 更多