【问题标题】:Authenticate googleapis library in Google Cloud Function在 Google Cloud Function 中验证 googleapis 库
【发布时间】:2020-08-15 00:33:13
【问题描述】:

对于本地开发,大多数谷歌云客户端库都配置为使用GOOGLE_APPLICATION_CREDENTIALS 环境变量来定位正在使用的服务帐户的凭据,然后对该库进行身份验证。当部署到 GCP 时,它们同样不需要在代码中进行任何手动身份验证,而是使用它们的环境在幕后进行身份验证。这意味着大多数客户端库(例如 BigQuery、Cloud Storage 等)仅在 Cloud Functions 中运行,无需任何代码进行身份验证。但是,googleapis Nodejs client library 不使用GOOGLE_APPLICATION_CREDENTIALS,并且似乎需要在代码中进行手动身份验证。下面是我如何在本地执行此操作的一个最小示例。如何在 Google Cloud Function 中运行此代码而无需将服务帐户凭据上传到云函数?

const { google } = require("googleapis");
const key = require("service_account_credentials.json");

const client = new google.auth.JWT(key.client_email, null, key.private_key, [
  "https://www.googleapis.com/auth/spreadsheets",
]);

client.authorize(function (err, tokens) {
  const gsapi = google.sheets({ version: "v4", auth: client });
  const opt = {
    spreadsheetId: "spreadsheetId",
    range: "Sheet1!A:T",
  };
  gsapi.spreadsheets.values.get(opt).then(res => console.log(res));
});

【问题讨论】:

  • 您误解了凭据在 Google Cloud 中的工作方式。环境变量只是一种方法,通常用于“开发人员代码”。查看 ADC,以便您了解 Google 库用于查找凭据的过程。在编写用于在云中执行的代码时,通常您希望使用分配给服务的服务帐户凭据,而不是服务帐户 JSON 文件。在您的回答中,您正在使用 ADC 来查找凭据。了解这个过程对于创建可靠、可部署的代码很重要cloud.google.com/docs/authentication/production

标签: node.js google-cloud-platform google-cloud-functions google-authentication


【解决方案1】:

我设法在 googleapis nodejs github repo 的readme.md 中找到了解决方案。为了解决我的问题,我使用了:


async function main() {
  const auth = new google.auth.GoogleAuth({
    scopes: ["https://www.googleapis.com/auth/spreadsheets"],
  });
  const authClient = await auth.getClient();
  const project = await auth.getProjectId();
  const gsapi = google.sheets({ version: "v4", auth: authClient });
  const opt = {
    spreadsheetId: "spreadsheetID",
    range: "Sheet1!A:T",
  };
  gsapi.spreadsheets.values.get(opt).then(res => console.log(res.data.values));
}

【讨论】:

    猜你喜欢
    • 2019-10-27
    • 2017-08-09
    • 2020-03-20
    • 1970-01-01
    • 2020-10-31
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多