代码之家  ›  专栏  ›  技术社区  ›  starsneverfall

无法从Facebook passport获取电子邮件信息

  •  1
  • starsneverfall  · 技术社区  · 6 年前

    目前,我正在进行一个项目,以存储来自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!');
      },
    );
    

    我不明白为什么我使用这种方式,而电子邮件信息仍然没有显示出来,这让我丢失了很多信息,有谁能给我一个解决这个问题的提示吗?非常感谢。

    1 回复  |  直到 6 年前
        1
  •  4
  •   Daksh M.    6 年前

    这个问题已经存在了一段时间,您需要包括电子邮件范围,即使这样,它也可能不会发送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.