Search code examples
node.jsoauth-2.0passport.jspassport-facebook

Passport Facebook Authentication Returns Undefined?


My facebook strategy is as follows:

passport.use(new facebookStrategy({

    clientID: envVars.facebook.clientID,
    clientSecret: envVars.facebook.clientSecret,
    callbackURL: envVars.facebook.callbackURL,
    passReqToCallback : true,
    profileFields: ['id', 'emails', 'displayName']
},

function(token, refreshToken, profile, done) {
    console.log(profile); //prints out undefined
}
));

And my routes are handled as follows:

router.get('/facebook', passport.authenticate('facebook'));

router.get('/auth/facebook/redirect', passport.authenticate('facebook'), 
function(req, res){
    res.redirect("/profile");
});

What my code manages to do successfully is direct the user to Facebook where they are prompted with a permission to allow my app to access their data. Once accepted my console.log(profile) fires yet it prints out undefined even though the user accepts the permission? I have searched through the documentation and can't seem to figure out where I went wrong.


Solution

  • Seems to be a problem with passReqToCallback. Refer this SO question: Using PassportJS, how does one pass additional form fields to the local authentication strategy?

    In your case, remove the passReqToCallback:true flag.

    passport.use(new facebookStrategy({
    
        clientID: envVars.facebook.clientID,
        clientSecret: envVars.facebook.clientSecret,
        callbackURL: envVars.facebook.callbackURL,
        profileFields: ['id', 'emails', 'displayName']
    },
    

    The other option is to modify your callback and use the first argument, which is the request object.

    function(req, email, password, done) {
        // now you can check req.body.foo
    }