首页 > 解决方案 > passport-github2 在电子邮件字段中返回 null

问题描述

passport-github2在电子邮件字段中返回 null,即使{scope: ['user:email']}已传递给passport.authenticate('github', {scope: ['user:email'] , session: false})(req, res, next)

标签: node.jsexpresspassport.jspassport-github2

解决方案


在查看源代码后,我发现存在一个获取用户电子邮件的函数,但为此,我们需要传递初始化GitHubStrategy. 我不确定为什么它没有在任何地方记录!为了让它正常工作,我发现我们需要做以下事情:

passport.use(new GitHubStrategy({
      clientID: GITHUB_OAUTH_CLIENT_ID,
      clientSecret: GITHUB_OAUTH_CLIENT_SECRET,
      callbackURL: GITHUB_OAUTH_CALLBACK,
      proxy: true,
      scope: ['user:email'] //This is all it takes to get emails
    }, (accessToken, refreshToken, profile, next) => {


// You get the profile object with emails array which can be accessed with 
// profile.emails[n].value

    }));

//middleware
passport.authenticate('github',  {scope: ['user:email']  , session: false})(req, res, next)

他们的回购中没有记录它真的很奇怪。

注意:由于对于 GitHub,如果用户设置为私有,则无法直接获取电子邮件地址,您需要调用另一个端点(docs)。它写在源代码中:(source

PS:我仍在寻找一种更好的方式来访问电子邮件,而无需在两个地方超出范围。


推荐阅读