【问题标题】:How to get email and profile information from OAuth2 Google API?如何从 OAuth2 Google API 获取电子邮件和个人资料信息?
【发布时间】:2017-09-24 11:39:18
【问题描述】:

我正在尝试使用 OAuth2 API 使用 Google API Node.js 客户端检索登录用户的名称。

按照使用示例,我设法进行了登录,但我找不到获取个人资料信息的方法。

我没有使用 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,例如 Google Sheets,可以像这样调用它们的函数:

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 不能那样工作......

【问题讨论】:

    标签: node.js google-api oauth-2.0


    【解决方案1】:

    2021 解决方案

    这个答案可能会偏离最初提出的问题,但我认为这对于一些通过生成 AuthUrl 并将其发送到客户端然后在调用中接收数据响应在后端获取谷歌用户信息的人来说会很有用用户给予客户端许可后返回的URL。

    一些全局声明

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

    使用范围生成 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
    

    在回调中获取用户数据

    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
    

    如有任何困惑或错误,欢迎在 cmets 中讨论

    【讨论】:

      【解决方案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: '#####'
      }
      

      【讨论】:

      • 我不太确定这是我正在寻找的答案。正如我之前所说,我有googleapis.com/auth/userinfo.profilegoogleapis.com/auth/userinfo.email 的范围,所以即使我不打算检查邮件,我是否真的需要包含 gmail 范围?
      • 查看 gmail.users.getProfile 响应,它有电子邮件地址、ID、总消息和总线程,但没有关于用户个人资料信息。所以我恐怕不能接受这个作为正确答案
      • 很抱歉我的误解。我将答案更新为“已添加”。请检查一下。该示例使用oauth2.userinfo.get检索用户信息。
      • 谢谢,它有效。我可以看到这与我的问题链接上的答案并没有什么不同,也许我做错了,没有注意到
      • 欢迎。我很高兴能帮上忙。
      【解决方案3】:

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

      http://passportjs.org/

      【讨论】:

      • 感谢您的回答,但我的问题不在于身份验证。查看 Passport.js,我发现 OAuth 与 OpenID 不同。很高兴知道
      猜你喜欢
      • 2021-01-16
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多