如何将有效的 OAuth2 访问令牌与适用于 Google People API 的 NodeJS SDK 结合使用

问题描述 投票:0回答:2

我不明白 Google 文档或代码文档如何通过 googleapis people 模块中的方法使用访问令牌。

我的用例是获取用户的电话号码以在我的应用程序中创建帐户。我接受访问令牌并验证它并检查其范围,如 Google 文档中所述:使用 OAuth 2.0 访问 Google API

该文档中的第 4 步说“将访问令牌发送到 API” - 然后他们概述了将其包含在标头中的过程。但我正在使用 NodeJS SDK,因此我试图弄清楚如何将访问令牌传递给我的

people
构造函数或正确的方法。

从正确的方法开始,我的参数似乎是

personFields
resourceName
sources
- 这些参数都不适合访问令牌。

所以我查看了

people
构造函数:

export declare function people(version: 'v1'): people_v1.People;
export declare function people(options: people_v1.Options): people_v1.People;

我注意到第二个使用 version 属性扩展了 GlobalOptions。 GlobalOptions 使用 auth 属性扩展 MethodOptions(等等)。这似乎是正确的(至少在名称上)。我看到 auth 属性的类型是:

auth?: GoogleAuth | OAuth2Client | BaseExternalAccountClient | string;

在这些类型中,似乎

string
将是我的目标 - 但没有很好的文档说明它想要什么。

我缺少什么 - 我在哪里输入此访问令牌?在详细介绍 people_v1 选项的 people_v1 部分中,我看到有一个名为 StandardParameters 的接口 - 并且 access_token 就在那里!但我不明白为什么它在那里或如何使用它。

google-api-nodejs-client
2个回答
0
投票

我有一个简单的 Oauth 客户端测试示例,可能会有所帮助:

/**
 * Simple Oauth Test to make sure that the Oauth flow is working,
 * Does NOT store tokens.
 */

'use strict';

const fs = require('fs');
const path = require('path');
const http = require('http');
const url = require('url');
const opn = require('open');
const destroyer = require('server-destroy');

const {
  google
} = require('googleapis');
const people = google.people('v1');

/**
 * To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI.  To get these credentials for your application, visit https://console.cloud.google.com/apis/credentials.
 */
const keyPath = path.join(__dirname, 'private/client_secret.....apps.googleusercontent.com.json');
let keys = {
  redirect_uris: ['']
};
if (fs.existsSync(keyPath)) {
  keys = require(keyPath).web;
}

/**
 * Create a new OAuth2 client with the configured keys.
 */
const oauth2Client = new google.auth.OAuth2(
  keys.client_id,
  keys.client_secret,
  keys.redirect_uris[0]
);

/**
 * This is one of the many ways you can configure googleapis to use authentication credentials.  In this method, we're setting a global reference for all APIs.  Any other API you use here, like google.drive('v3'), will now use this auth client. You can also override the auth client at the service and method call levels.
 */
google.options({
  auth: oauth2Client
});

/**
 * Open an http server to accept the oauth callback. In this simple example, the only request to our webserver is to /callback?code=<code>
 */
async function authenticate(scopes) {
  return new Promise((resolve, reject) => {
    // grab the url that will be used for authorization
    const authorizeUrl = oauth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: scopes.join(' '),
    });
    const server = http
      .createServer(async (req, res) => {
        try {
          if (req.url.indexOf('/oauth2callback') > -1) {
            const qs = new url.URL(req.url, 'http://localhost:3000')
              .searchParams;
            res.end('Authentication successful! Please return to the console.');
            server.destroy();
            const {
              tokens
            } = await oauth2Client.getToken(qs.get('code'));
            oauth2Client.credentials = tokens; // eslint-disable-line require-atomic-updates
            resolve(oauth2Client);
          }
        } catch (e) {
          reject(e);
        }
      })
      .listen(3000, () => {
        // open the browser to the authorize url to start the workflow
        opn(authorizeUrl, {
          wait: false
        }).then(cp => cp.unref());
      });
    destroyer(server);
  });
}

async function runSample() {
  // retrieve user profile
  const res = await people.people.get({
    resourceName: 'people/me',
    personFields: 'emailAddresses',
  });
  console.log(res.data);
}

const scopes = [
  'https://www.googleapis.com/auth/contacts.readonly',
  'https://www.googleapis.com/auth/user.emails.read',
  'profile',
];


async function test() {
  let client = await authenticate(scopes);
  await runSample(client);
}

test();

使用您自己的“private/client_secret.....apps.googleusercontent.com.json”,它应该可以工作。


0
投票

您可以在标头中传递令牌(该库允许您修改 Gaxios 标头):

google.options({
    headers: {
        Authorization: `Bearer ${your_access_token_here}`
    }
});

// use the googleapis sdk, example:
const drive = google.drive({
  version: 'v3'
});

const res = await drive.files.create({
  requestBody: {
    name: 'Test',
    mimeType: 'text/plain'
  },
  media: {
    mimeType: 'text/plain',
    body: 'Hello World'
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.