【问题标题】:Can't get email information from Facebook passport无法从 Facebook 护照中获取电子邮件信息
【发布时间】:2018-08-10 09:21:29
【问题描述】:

目前我正在做一个项目来存储来自 Facebook 身份验证的信息,我已经检查了Passport-facebook doesn't get email 以查看解决方案,这是我的代码

passport.use(new FacebookStrategy(
  {
    clientID: 'xxxxxxxxxxxxx',
    clientSecret: 'xxxxxxxxxxxxxxxx',
    callbackURL: 'http://1bc600b4.ngrok.io/auth/facebook/callback',
    profileFields: ['id', 'displayName', 'name', 'photos', 'email'],
  },
  (accessToken, refreshToken, profile, done) => {
    console.log(profile);
    models.User.findOne({ where: { facebookID: profile.id } }).then((existinguser) => {
      if (existinguser) {
        // Nothing will happen, the ID already exists
        done(null, existinguser);
      } else {
        models.User.create({
          // email: profile.emails[0].value,
          username: 'hello',
          firstname: profile.name.givenName,
          lastname: profile.name.familyName,
          facebookID: profile.id,
          avatar: `https://graph.facebook.com/${profile.id}/picture?redirect=true&height=470&width=470`,
          avatarThumb: profile.photos[0].value,
          last_login: Date.now(), }).then(user => done(null, user));
      }
    });
  },
));

app.use(passport.initialize());

app.get('/flogin', passport.authenticate(
  'facebook',
  passport.authenticate('facebook', { scope: ['profile', 'email'] }),
));

app.get(
  '/auth/facebook/callback',
  passport.authenticate('facebook', { session: false }),
  (req, res) => {
    res.send('AUTH WAS GOOD!');
  },
);

我不明白为什么我使用这种方式并且电子邮件信息仍然没有显示,这让我失去了很多信息,谁能给我一个解决这个问题的提示?谢谢!

【问题讨论】:

    标签: node.js passport.js passport-facebook


    【解决方案1】:

    这个问题已经存在了一段时间,您需要包含电子邮件范围,即使这样,由于用户隐私设置或如果用户的电子邮件未在 facebook 端验证,它也可能不会发送 facebook 电子邮件。

    您可以像这样添加范围:

    passport.use(
       new FacebookStrategy({
                clientID: 'CLIENT_ID',
                clientSecret: 'CLIENT_SECRET',
                callbackURL: "http://www.example.com/auth/facebook/callback"
                passReqToCallback : true,
                profileFields: ['emails'] // email should be in the scope.
       })
    )
    

    您还需要将此添加到您的授权路线中,

    app.get('/login/facebook', passport.authorize('facebook', { scope : ['email'] }));
    

    如果电子邮件返回,它将是一个列表,您可以像这样访问它们:

    1. profile.emails // [email1@example.com, somerandomdude@gmail.com]
    2. profile.emails[1].value // randomdude@yahoo.com
    

    如果没有返回,您可以使用他们的用户名或 ID 并至少暂时创建一个 Facebook 电子邮件,如下所示:

    username@facebook.com // this exists.
    

    【讨论】:

    • 嗨,谢谢你的回答,我试了几次,发现这些代码对我有用,我发现我不需要在我的代码中添加 passReqToCallback ,否则它会一直显示 done is not一个函数
    • 太好了,很高兴知道它解决了您的问题!
    • 你是最棒的!
    猜你喜欢
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2016-02-06
    • 1970-01-01
    相关资源
    最近更新 更多