2016-02-12 131 views
11

我正在关注Github’s OAuth flow,并获取访问令牌,使我可以访问用户的电子邮件范围。当我访问令牌交换码,使用https://github.com/login/oauth/access_token终点,我得到如下回应:Github用户的电子邮件为空,尽管用户:电子邮件范围

{ 
    access_token: '83f42..xxx’, 
    token_type: 'bearer', 
    scope: 'user:email' 
} 

看起来不错。所以我提出这个请求,使用令牌来获得我的用户数据:

Accept-Language: en-us 
Accept: application/json 
Authorization: token 83f42..xxx 
Accept-Encoding: gzip, deflate 

GET https://api.github.com/user 

我确实得到我的用户对象作为响应,但email属性为空。任何人都有这个问题?

回答

22

我发现了为什么发生这种情况以及如何解决它。按照docs

注:返回的电子邮件是用户的公开可见的电子邮件地址 (或null如果他们 配置文件中的用户没有指定的公共电子邮件地址)。

在您的GitHub的配置文件设置,下公共电子邮件,一些用户(包括我自己)都该选项设置为“不显示我的电子邮件地址。”对/user的调用仅返回公共电子邮件地址,因此如果用户不希望显示该地址,那么API将尊重该地址。

enter image description here

要获得用户的电子邮件地址,无论他们是否是公开的,使用呼叫来/user/emails。你可以使用访问令牌中完全相同的方式作为/user要求:

Accept-Language: en-us 
Accept: application/json 
Authorization: token 83f42..xxx 
Accept-Encoding: gzip, deflate 

GET https://api.github.com/user/emails 

这个调用给我下面的JSON响应:

[ 
    { 
    "email": "[email protected]", 
    "primary": true, 
    "verified": true 
    } 
] 
+2

使用的node.js与护照github上,解决的办法是'范围通过:[“用户:电子邮件”]'到GitHubStrategy构造函数。请注意,您将获得用户电子邮件数组,如果您想要过滤“primary:true”,等等。 –

+0

@AntonDrukh您能否详细说明一下? '护照github'咒语会是什么? – Fergie

+0

@Fergie在下面看到我的回答,太长的评论。 –

4

@Fergie可能不适合评论这个,所以回答为node.js的passport-github情况:

var GitHubStrategy = require('passport-github').Strategy; 

passport.use('github-login', new GitHubStrategy({ 
    clientID: config.clientId, 
    clientSecret: config.secret, 
    callbackURL: config.host + config.callback, 
    passReqToCallback: true, // req object on auth is passed as first arg 
    scope: [ 'user:email' ], // fetches non-public emails as well 
}, 
    function (req, accessToken, refreshToken, profile, done) { 
    // find user by profile and update it 
    // or create the user object given the req, tokens and profile objs 
    // don't forget to call `done(null, user)` once done 
} 
));