【问题标题】:How do you authenticate on facebook using passport in a web application?您如何在 Web 应用程序中使用护照在 Facebook 上进行身份验证?
【发布时间】:2021-09-05 03:44:22
【问题描述】:

所以,我成功地使用节点包 passport-google-oauth20 在我正在编写的测试 Web 应用程序上对用户进行身份验证...这是代码:

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      callbackURL: 'http://localhost:3000/auth/google/secrets',
      userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo'
    },

    (accessToken, refreshToken, profile, done) => {
      User.findOne({ googleId: profile.id }).then(currentUser => {
        if (currentUser) {
          //if we already have a record with the given profile ID
          done(null, currentUser);
        } else {
          //if not, create a new user
          new User({
            googleId: profile.id
          })
            .save()
            .then(newUser => {
              done(null, newUser);
            });
        }
      });
    }
  )
);

但是,当我导入并尝试使用节点包 passport-facebook 时,如下所示:

passport.use(
  new FacebookStrategy(
    {
      clientID: process.env.FACEBOOK_APP_ID,
      clientSecret: process.env.FACEBOOK_APP_SECRET,
      callbackURL: 'http://localhost:3000/auth/facebook/secrets'
    },

    (accessToken, refreshToken, profile, done) => {
      User.findOne({ facebookId: profile.id }).then(currentUser => {
        if (currentUser) {
          //if we already have a record with the given profile ID
          done(null, currentUser);
        } else {
          //if not, create a new user
          new User({
            facebookId: profile.id
          })
            .save()
            .then(newUser => {
              done(null, newUser);
            });
        }
      });
    }
  )
);

我遇到了问题。在我的应用程序中,我到达了“使用 facebook 登录”屏幕。但是,应用程序只是挂起并给我一个错误而不是重定向。这是错误:

UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: userDB.users index: username_1 dup key: { username: null }

有没有人在使用 passport.js 身份验证策略时遇到过这种情况?

【问题讨论】:

  • 您正在从 google 添加用户,并将用户名字段设置为 null,然后对 facebook 执行相同操作。用户名字段设置为 mongodb 集合中的索引。每当有人通过 passport.js 登录时尝试设置用户名字段
  • 感谢大家的帮助。我使用的是“电子邮件”而不是“用户名”......我更改了我的用户架构以使“电子邮件”字段成为“用户名”,并且用户是否输入电子邮件或文本,因为用户名变得无关紧要。然后,在 mongodb 中,如果用户手动注册(使用本地身份验证),则用户名将成为用户在输入字段中键入的名称。但是,如果用户选择 Google 或 Facebook 身份验证,则用户名将作为用户在相关平台(GoogleId 或 FacebookId)上的配置文件 ID 存储在 mongoDB 中。

标签: javascript node.js mongodb passport.js


【解决方案1】:

从 currentUser 或 newUser 返回的用户名属性为空,并且您在 MongoDB 中的用户名字段被标记为唯一。您的 MongoDB 集合中已经有一条记录为空,因此它会将其视为重复记录。我不会使用用户名作为您的唯一键,而是为每个用户分配一个 uuid,但请检查您的数据库以确保用户名是唯一的。

您可以尝试 console.log 您的 newUser 或 currentUser 对象,并找出用户名返回为 null 的原因。

我个人只将 Passport.js 用于 Linkedin 和 Twitter,但我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-09-24
    • 1970-01-01
    • 2023-04-04
    • 2010-09-12
    • 2016-10-02
    • 2017-01-02
    • 2023-04-04
    • 2013-09-04
    • 2016-01-19
    相关资源
    最近更新 更多