karlkurzer karlkurzer - 2 months ago 16
Node.js Question

facebook node passport does not return email address

Hello people I have been looking in several places also here

134 Email key is not returned when trying to authenticate a user
https://github.com/jaredhanson/passport-facebook/issues/134

I'll paste the standard passport Facebook code.
I specified the profile fields as well. The problem is that the request to FB doesn't fetch the email address of the user, which is essential for my application.

// Load the module dependencies
var passport = require('passport'),
url = require('url'),
FacebookStrategy = require('passport-facebook').Strategy,
config = require('../config'),
users = require('../../app/controllers/users.server.controller');

// Create the Facebook strategy configuration method
module.exports = function() {
// Use the Passport's Facebook strategy
passport.use(new FacebookStrategy({
clientID: config.facebook.clientID,
clientSecret: config.facebook.clientSecret,
callbackURL: config.facebook.callbackURL,
profileFields: ["id", "birthday", "email", "first_name", "gender", "last_name"],
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
// Set the user's provider data and include tokens
var providerData = profile._json;
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;

console.log(profile);
var email = profile.emails ? profile.emails[0].value : 'karl.something@something.com';

// Create the user OAuth profile
var providerUserProfile = {
firstName: profile.name.givenName,
lastName: profile.name.familyName,
fullName: this.firstName + ' ' + this.lastName,
email: email,
username: profile.username,
provider: 'facebook',
providerId: profile.id,
providerData: providerData
};

// Save the user OAuth profile
users.saveOAuthUserProfile(req, providerUserProfile, done);
}
));
};


Here you can see the console.log(profile) output:

{ id: '894894191844',
username: undefined,
displayName: undefined,
name: { familyName: 'Something', givenName: 'Karl', middleName: undefined },
gender: 'male',
profileUrl: undefined,
provider: 'facebook',
_raw: '{"id":"1197051993654521","first_name":"Karl","gender":"male","last_name":"Something"}',
_json:
{ id: '1197051993654521',
first_name: 'Karl',
gender: 'male',
last_name: 'Koks',
accessToken: 'XYZ',
refreshToken: undefined } }


Any concrete ideas, would like to fix this issue soon :-)

Answer

possibly not the only solution but the following worked for me:

from

passport.authenticate('facebook');

to

passport.authenticate('facebook', { scope: 'email'}));

then the field emails will be populated

Answer found here: passport-facebook - cant get about_me and email profile fields