Search code examples
node.jsauthenticationpassport.jsgithub-oauthpassport-github2

How to use passport.js github strategy to get emails of users instead of null


I successfully got the user details but the email field is null.After some time got to know that I need to fetch it from "https://api.github.com/user/emails".I used axios and also provided accesstoken as header but it is giving me "▼♥��A�@►���\�%♥+=y��5"V↔ubWevW�迧F�¶◄t��☻�%)H�ɢ�k��♥葩$,�7↓�H�↔?��^Z�k�r���:��x�▬♣▬NP������҇�C�v�C▼o.�pK~☺" instead of emails.

passport.use(new GitHubStrategy({
    clientID: process.env.GITHUB_CLIENT_ID,
    clientSecret: process.env.GITHUB_CLIENT_SECRET,
    callbackURL: "/callbackurl"
  },
  function(accessToken, refreshToken, profile, done) {
  User.findOrCreate({ githubId: profile.id }, function (err, user){   //I am using mongoose-findorcreate npm
      axios.get('https://api.github.com/user/emails', {
 headers: {
   "Authorization": "Bearer "+ accessToken,
 }
}).then((res)=>{
  console.log(res.data);
})
      return done(err, user);
    });
  }
));

Solution

  • It's because you have not specified scope inside your strategy so Inside your github Strategy , also include scope key: scope: ["user:email"], As:

    `new GitHubStrategy({
        clientID: process.env.GITHUB_CLIENT_ID,
        clientSecret: process.env.GITHUB_CLIENT_SECRET,
        callbackURL: "/callbackurl",
        scope: ["user:email"]
    }`