2017-04-26 150 views
1

我试图使用Google API Node.js客户端,使用OAuth2 API检索登录用户的名称。如何从OAuth2 Google API获取电子邮件和个人资料信息?

按照使用示例,我设法做了登录,但我找不到获取配置文件信息的方法。

我没有使用People API和Plus API,因为据我所知,OAuth2包含https://www.googleapis.com/auth/userinfo.profile,这应该足够用于该任务。

我已经看到了一些类似的问题,并试图这样一个的解决方案,但它没有工作,也许是太旧(?)

With the npm package googleapis how do I get the user's email address after authenticating them?

看着其他的API像谷歌表,这是可能的调用其功能是这样的:

var google = require('googleapis'); 
var sheets = google.sheets('v4'); 

... 

sheets.spreadsheets.values.get({ 
    auth: auth, 
    spreadsheetId: file_id, 
    range: my_ranges, 
    }, function(err, response){ 
     ... 
    } 
); 

但似乎OAuth2用户不喜欢的工作......

回答

2

您可以ü快速启动node.js.详细信息是https://developers.google.com/gmail/api/quickstart/nodejs。使用Quickstart中的示例脚本,您可以通过OAuth2检索访问令牌,并检索电子邮件和用户配置文件。

之前,它运行快速入门的样本,请确认先决条件,步骤1和步骤2

你可以通过改变listLabels(auth)按如下方式使用。范围是https://www.googleapis.com/auth/gmail.readonly

脚本:

var gmail = google.gmail({ 
     auth: auth, 
     version: 'v1' 
}); 

gmail.users.getProfile({ 
    auth: auth, 
    userId: 'me' 
    }, function(err, res) { 
    if (err) { 
     console.log(err); 
    } else { 
     console.log(res); 
    } 
}); 

gmail.users.messages.get({ 
    'userId': 'me', 
    'id': 'mail ID', 
    'format': 'raw' 
}, function (err, res) { 
    console.log(new Buffer(res.raw, 'base64').toString()) 
}); 
  • gmail.users.getProfile检索用户配置文件。
  • gmail.users.messages.get检索电子邮件。

如果我误解你的问题,我很抱歉。

补充:

以上请改为下面的脚本。范围是https://www.googleapis.com/auth/userinfo.profile

脚本:

var oauth2 = google.oauth2({ 
     auth: auth, 
     version: 'v2' 
}); 

oauth2.userinfo.v2.me.get(
function(err, res) { 
    if (err) { 
     console.log(err); 
    } else { 
     console.log(res); 
    } 
}); 

结果:

{ 
    id: '#####', 
    name: '#####', 
    given_name: '#####', 
    family_name: '#####', 
    link: '#####', 
    picture: '#####', 
    gender: '#####', 
    locale: '#####' 
} 
+0

我不确定这是我正在寻找的答案。正如我前面所说,我有https://www.googleapis.com/auth/userinfo的范围。配置文件和https://www.googleapis.com/auth/userinfo.email,所以即使我不打算检查邮件,我是否真的需要包含gmail范围? – amlibtest

+0

查看gmail.users.getProfile响应,它具有电子邮件地址,id,总消息和总线程数,但没有关于用户配置文件信息。所以恐怕我不能接受这个作为正确的答案 – amlibtest

+0

我很抱歉我的误解。我将我的答案更新为“已添加”。请检查一下。该示例使用''oauth2.userinfo.get''检索用户信息。 – Tanaike

0

您也可以看看PassportJS。他们有多种策略,包括OAuth2和3种不同的Google Auth策略。我的回答并没有真正回答你的问题,但也许甚至在护照的代码采取偷看,你可能会得到你的答案。

http://passportjs.org/

+0

我很感谢你的回答,但我的问题不是认证。看看Passport.js,我发现OAuth与OpenID不同。很高兴知道 – amlibtest

相关问题