护照-Facebook未提供电子邮件,即使它在范围内

20
在我的应用程序中,我按照以下方式注册了Facebook策略:但是返回的个人资料中不包含电子邮件字段...
passport.use(new FacebookStrategy({
        clientID: config.facebook.clientID,
        clientSecret: config.facebook.clientSecret,
        callbackURL: config.facebook.callbackURL,
        passReqToCallback: true
    },
    function(req, accessToken, refreshToken, profile, done) {
        // No email in the following colsole.log
        console.log(JSON.stringify(profile));
    }));

以下是get请求的内容:
app.get('/oauth/facebook', passport.authenticate('facebook', {
    failureRedirect: '/login',
    scope:['email']
}));

我正在使用范围(scope),如此处所述:Passport-facebook doesn't get email

在FB登录页面上,我甚至被要求输入电子邮件地址,并且我已经提供了它:

enter image description here

非常感谢任何帮助!


你需要同时请求电子邮件字段。 - WizKid
我该怎么做?我以为可以用 scope:['email'] 来实现。 - Rentrop
scope:['email'] 是您想要的权限。当您调用 /me 时,您需要执行 /me?fields=email。 - WizKid
3个回答

70

从 Facebook Graph API v2.4 开始,我们需要明确指定要获取的字段。

介绍 Graph API v2.4

因此,我们可以这样写:

  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'email', 'gender', 'link', 'locale', 'name', 'timezone', 'updated_time', 'verified'],
    },

10
我很惊讶官方的passport.js文档中没有提到这一点。 - kmansoor

2

你是否已经有了代码的回调部分呢?


app.get('/oauth/facebook/callback', passport.authenticate('facebook', {
    failureRedirect: '/login',
    successRedirect: '/',
    scope:['email']
}));

是的,确实需要使用scope:['email']来完成此操作,根据您提供的链接和这里的说明。


是的,我在回调中也有这个电子邮件... 这很奇怪。 - Rentrop

1

您需要指定范围:"email"。请参考以下代码。

Facebook身份验证路由:

// auth facebook
router.get("/auth/facebook", passport.authenticate("facebook", {
  scope: "email"
}));

在配置FacebookStrategy时,您还需要指定profileFields。

passport.use(new FacebookStrategy({
  callbackURL: "http://localhost:5000/auth/facebook/redirect",
  clientID: keys.facebook.clientID,
  clientSecret: keys.facebook.clientSecret,
  profileFields: ['id', 'displayName', 'photos', 'email', 'gender', 'name']
}, (accessToken, refreshToken, profile, done) => {
   // logic 
}))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接