在 Node.js 中使用 Google API :避免重复授权

Using Google API in Node.js : Avoiding repetitive authorization

我正在尝试构建一个 API,每次收到请求时都需要查看我的 Google 日历(而不是发送请求的用户的日历)。我的 API 应该能够响应用户的请求,而无需一次又一次地要求我进行身份验证。此 API 目前托管在 Heroku 上。

为此,我正在关注 Quickstart 项目。访问令牌存储在此项目的 token.json 文件中。我不明白这个项目如何处理访问令牌的到期。在这个 Quickstart 项目中,我无法确定访问令牌被刷新并重写为 token.json 的位置。我们只在第一次创建文件时写入 token.json 文件,此后再也不会写入。在这个项目中,访问令牌将如何在到期时刷新?

我也不知道应该在哪里存储 token.json 文件。我尝试手动授权 API 然后将获得的令牌作为环境变量存储在 heroku 上。它昨天工作正常,但今天给出 The API returned an error: Error: unauthorized_client,我认为我的令牌已过期。每次用户向 API 发送 HTTP 请求时,如何确保 API 不需要我这边的重复授权?

您可以创建服务帐户并通过 google 云 IAM 和管理生成 service-key.json 文件: screenshot of where IAM & Admin can be found

然后,在您的代码中,您可以使用服务帐户进行授权:

import {google} from 'googleapis';

const initAuth = async () => {
  const auth = new google.auth.GoogleAuth({
    keyFile: './service-key.json', //path to service-key.json
    scopes: ['https://www.googleapis.com/auth/drive'], //any auth scopes
  });

  const authClient = await auth.getClient();
  google.options({auth: authClient});
};