简体   繁体   English

如何从 OAuth2 Google API 获取电子邮件和个人资料信息?

[英]How to get email and profile information from OAuth2 Google API?

I'm trying to retrieve the name of a logged in user using Google API Node.js Client, using OAuth2 API.我正在尝试使用 OAuth2 API 使用 Google API Node.js 客户端检索登录用户的名称。

Following the usage example, I managed to do the login, but I can't find a way to get the profile information.按照用法示例,我设法进行了登录,但找不到获取个人资料信息的方法。

I'm not using People API nor Plus API, cause as far as i know, OAuth2 includes https://www.googleapis.com/auth/userinfo.profile , which should be enough for the task.我没有使用 People API 或 Plus API,因为据我所知,OAuth2 包括https://www.googleapis.com/auth/userinfo.profile ,这应该足以完成任务。

I have seen some similar questions and tried the solutions of this one but it didn't work, maybe it's too old (?)我已经看到了一些类似的问题并尝试了这个的解决方案但是它没有用,也许它太旧了(?)

With the npm package googleapis how do I get the user's email address after authenticating them? 使用 npm 包 googleapis 如何在验证用户身份后获取用户的电子邮件地址?

Looking at other API's like Google Sheets, it's possible to call their functions like this:查看其他 API,例如 Google 表格,可以这样调用它们的函数:

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

...

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

But it seems that OAuth2 doesn't work like that...但似乎 OAuth2 不是那样工作的......

You can use Quickstart for node.js.您可以使用 node.js 的快速入门。 The detail information is https://developers.google.com/gmail/api/quickstart/nodejs .详细信息是https://developers.google.com/gmail/api/quickstart/nodejs Using a sample script from Quickstart, you can retrieve access token by OAuth2, and retrieve email and user profile.使用 Quickstart 中的示例脚本,您可以通过 OAuth2 检索访问令牌,并检索电子邮件和用户配置文件。

Before it runs a sample of Quickstart, please confirm Prerequisites, Step 1 and Step 2.在运行 Quickstart 示例之前,请确认先决条件、步骤 1 和步骤 2。

You can use by changing listLabels(auth) as follows.您可以通过如下更改listLabels(auth)来使用。 The scope is https://www.googleapis.com/auth/gmail.readonly .范围是https://www.googleapis.com/auth/gmail.readonly

Script:脚本:

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 retrieves user profile. gmail.users.getProfile检索用户配置文件。
  • gmail.users.messages.get retrieves email. gmail.users.messages.get检索电子邮件。

If I misunderstand your question, I'm sorry.如果我误解了你的问题,我很抱歉。

Added:添加:

Please change above to following script.请将上面的脚本更改为以下脚本。 Scope is https://www.googleapis.com/auth/userinfo.profile .范围是https://www.googleapis.com/auth/userinfo.profile

Script:脚本:

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);
    }
});

Result:结果:

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

2021 Solution 2021年解决方案

This answer may divert from the originally asked question but I think it will be useful for some people who are getting google user information in the backend by generating AuthUrl and sending it to the client side and then receiving the data response in the call back URL after the user gives permission from the client side.这个答案可能会偏离最初提出的问题,但我认为这对于某些通过生成 AuthUrl 并将其发送到客户端然后在回调 URL 中接收数据响应而在后端获取 google 用户信息的人很有用用户从客户端授予权限。

Some global declarations一些全局声明

import { google } from "googleapis";
const Oauth2Client = new google.auth.OAuth2(
  googleCredentials.CLIENT_ID,
  googleCredentials.CLIENT_SECRET,
  googleCredentials.REDIRECT_URI
);

Generate the Auth URL with the scopes使用范围生成 Auth URL

const SCOPE = [
  'https://www.googleapis.com/auth/userinfo.profile', // get user info
  'https://www.googleapis.com/auth/userinfo.email',   // get user email ID and if its verified or not
];
const auth_url = Oauth2Client.generateAuthUrl({
  access_type: "offline",
  scope: SCOPE,
  prompt: "consent",
  state: "GOOGLE_LOGIN",
});
return res.json({ url: auth_url });    // send the Auth URL to the front end

Get the user data in the callback在回调中获取用户数据

let code = req.query.code;    // get the code from req, need to get access_token for the user 
let { tokens } = await Oauth2Client.getToken(code);    // get tokens
let oauth2Client = new google.auth.OAuth2();    // create new auth client
oauth2Client.setCredentials({access_token: tokens.access_token});    // use the new auth client with the access_token
let oauth2 = google.oauth2({
  auth: oauth2Client,
  version: 'v2'
});
let { data } = await oauth2.userinfo.get();    // get user info
console.log(data);    // you will find name, email, picture etc. here

Feel free to discuss in the comments if there's any confusion or error如果有任何混淆或错误,请随时在评论中讨论

You can also look into PassportJS.您还可以查看 PassportJS。 They have multiple strategies, including OAuth2 and 3 different Google Auth strategies.他们有多种策略,包括 OAuth2 和 3 种不同的 Google Auth 策略。 My answer doesn't really answer your question but maybe even taking a peek at Passport's code, you may get your answer.我的回答并没有真正回答您的问题,但即使看一眼 Passport 的代码,您也可能会得到答案。

http://passportjs.org/ http://passportjs.org/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何访问谷歌 Oauth2 护照中的个人资料信息? - How can I access profile information in google Oauth2 passport? Google OAuth2 无法获取个人资料信息 - Google OAuth2 cannot get profile info 如何使用 OAuth2 和 PassportJS 获取 Google Fitness API 数据 - How to get Google Fitness API data using OAuth2 with PassportJS 如何使用nodejs google api从没有浏览器的EC2实例获取OAuth2令牌 - How to get OAuth2 token from an EC2 instance with no browser using nodejs google api 配置文件中缺少 Google OAuth 2.0 email - Google OAuth 2.0 email missing from profile 如何使用 OAuth2 客户端从 Dialogflow Fulfillment 验证 Google Calendar API? - How to authenticate Google Calendar API from Dialogflow Fulfillment using OAuth2 Client? 从授权码google oauth2获取刷新令牌 - get refresh token from authorization code google oauth2 如何在 google oauth2 中使用刷新令牌获取访问令牌? - How to get access token using refresh token in google oauth2? 如何从 Google API 获取用户信息配置文件? - How I can get user info profile from Google API? Google OAuth2 API刷新令牌 - Google OAuth2 API Refresh Tokens
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM