email field is optional in passportjs facebook strategy

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 04:29:46

I solved the problem by re-requesting the permission.

Turns out I can add authType: 'rerequest' to passport.authenticate('facebook', {scope: ['email'], authType: 'rerequest'}).

What I did is to check if the emails field is present in the result, if not, I call done with an error.

function(accessToken, refreshToken, profile, done) {
    if (profile.emails === undefined) {
        done('email-required')
        return;
    }
    // doing the rest of the thing
}

Then to catch the error, I had to write a custom callback for passport.authenticate('facebook').

app.get('/auth/facebook/cb', function(req, res, next) {
    passport.authenticate('facebook', function (err, user, info) {
        if (err) {
            if (err == 'email-required') res.redirect('/auth/facebook/rerequest');
            // check for other kinds of errors and show proper messages
            return;
        }
        req.user = user;
        // do the rest of the thing
    })(req, res, next)
});

As you see, I redirect the user to another route /auth/facebook/rerequest in case of error.

app.get('/auth/facebook/rerequest',
    passport.authenticate('facebook', {
        scope: ['email'],
        authType: 'rerequest' // this is important
    }
));

This will redirect the user to the same page on FB again and this time email field is required. I couldn't do this in the same route; apparently it was using the same generated code to communicate to fb which was not acceptable by fb.

And that's how I managed to solve the issue.

you need to specify email in Strategy in profileFields property

passport.use('facebook', new FacebookStrategy({
  clientID: config.facebook.appId,
  clientSecret: config.facebook.appSecret,
  callbackURL: config.facebook.callbackURL,
  profileFields: ['emails', 'first_name', 'last_name', 'locale', 'timezone']
}, function (token, refreshToken, profile, done) {
  // you will get emails in profile.emails
}));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!