如何使用节点google客户端api获取已获取令牌的用户配置文件?

s-h*_*ter 7 google-api node.js google-api-client

通过curl获取用户个人资料信息

curl -i https://www.googleapis.com/userinfo/v2/me -H "Authorization: Bearer a-google-account-access-token"
Run Code Online (Sandbox Code Playgroud)

通过节点https获取请求获取用户配置文件信息

const https = require('https');

function getUserData(accessToken) {
    var options = {        
                    hostname: 'www.googleapis.com',
                    port: 443,
                    path: '/userinfo/v2/me',
                    method: 'GET',
                    json: true,
                    headers:{
                        Authorization: 'Bearer ' + accessToken            
                   }
            };
    console.log(options);
    var getReq = https.request(options, function(res) {
        console.log("\nstatus code: ", res.statusCode);
        res.on('data', function(response) {
            try {
                var resObj = JSON.parse(response);
                console.log("response: ", resObj);
            } catch (err) {
                console.log(err);
            }
        });
    });

    getReq.end();
    getReq.on('error', function(err) {
        console.log(err);
    }); 

}

var token = "a-google-account-access-token";
getUserData(token)
Run Code Online (Sandbox Code Playgroud)

如果我已经拥有访问令牌,如何使用此google node api客户端库获取用户个人资料信息?我可以使用上面的代码来获取配置文件,但我认为最好使用谷歌api库来做到这一点,但我无法弄清楚如何使用这个节点google api客户端库.

可以通过玩这个游乐场获取临时访问令牌

Tan*_*ike 16

您可以使用google node api客户端库检索用户个人资料.在这种情况下,请检索访问令牌和刷新令牌作为范围https://www.googleapis.com/auth/userinfo.profile.示例脚本如下.使用此示例时,请设置您的ACCESS TOKEN.

示例脚本:

var google = require('googleapis').google;
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2();
oauth2Client.setCredentials({access_token: 'ACCESS TOKEN HERE'});
var oauth2 = google.oauth2({
  auth: oauth2Client,
  version: 'v2'
});
oauth2.userinfo.get(
  function(err, res) {
    if (err) {
       console.log(err);
    } else {
       console.log(res);
    }
});
Run Code Online (Sandbox Code Playgroud)

结果:

{
  id: '#####',
  name: '#####',
  given_name: '#####',
  family_name: '#####',
  link: '#####',
  picture: '#####',
  gender: '#####',
  locale: '#####'
}
Run Code Online (Sandbox Code Playgroud)

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

  • @s-hunter 我总是从 README.md 和每个使用 Google API 的客户端库的源中获取信息。关于“setCredentials”,我从[文档](https://github.com/google/google-api-nodejs-client/blob/master/README.md) 得到它。从这些信息中,我可以了解如何使用“oauth2Client”。然后,关于 Node.js 的“oauth2.userinfo.get”,我检查了 [this](https://github.com/google/google-api-nodejs-client/blob/da49e69e272653cb94a248e60f73656b90ba387f/apis/oauth2/v2 .ts)。我认为还有更有效的方法。但在这种情况下,我在上面做了。如果这没有用,我很抱歉。 (2认同)

win*_*__7 10

2021年解决方案

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

一些全局声明

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

生成具有范围的 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
Run Code Online (Sandbox Code Playgroud)

在回调中获取用户数据

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);
Run Code Online (Sandbox Code Playgroud)

如果有任何困惑或错误,请随时在评论中讨论