Passport-Facebook authentication is not providing email for all Facebook accounts

前端 未结 7 972
忘了有多久
忘了有多久 2020-12-07 20:16

I am using Passport-Facebook authentication.

  passport.use(new FacebookStrategy({
            clientID: \'CLIENT_ID\',
            clientSecret: \'CLIENT_SECRET\         


        
7条回答
  •  孤街浪徒
    2020-12-07 20:50

    When passport doesn't return the profile.emails, profile.name.givenName, profile.name.familyName fields, or if they are missing, you can try to parse the https://graph.facebook.com/v3.2/ url, although you still need a token. You access the url, with of course a valid token, like:

    https://graph.facebook.com/v3.2/me?fields=id,name,email,first_name,last_name&access_token=

    It outputs a JSON response like:

    {
       "id": "5623154876271033",
       "name": "Kurt Van den Branden",
       "email": "kurt.vdb\u0040example.com",
       "first_name": "Kurt",
       "last_name": "Van den Branden"
    }
    

    Install the request module ($ npm install request --save), to be able to parse a JSON url and in your passport.js file:

    const request = require("request");
    
    passport.use(new FacebookStrategy({
            clientID        : 'CLIENT_ID',
            clientSecret    : 'CLIENT_SECRET',
            callbackURL     : "https://example.com/auth/facebook/callback"
        },
        function(req, token, profile, done) {
    
            let url = "https://graph.facebook.com/v3.2/me?" +
                      "fields=id,name,email,first_name,last_name&access_token=" + token;
    
            request({
                url: url,
                json: true
            }, function (err, response, body) {
                  let email = body.email;  // body.email contains your email
                  console.log(body); 
            });
        }
    ));
    

    You can add a lot of other parameters to the url, although some of them require user permission to return values. You can play with it on: https://developers.facebook.com/tools/explorer/

提交回复
热议问题