1
votes

For developing locally, most google cloud client libraries are configured to use the GOOGLE_APPLICATION_CREDENTIALS environment variable to locate the credentials for the service account in use, and then authenticate that library. When deployed to GCP, they similarly don't require any manual authentication in the code, and instead use they environment to authenticate behind the scenes. This means that most client libraries, for example BigQuery, Cloud Storage, etc, just work in Cloud Functions, without needing any code for authentication. However, the googleapis Nodejs client library doesn't use GOOGLE_APPLICATION_CREDENTIALS and seems to require manual authentication in the code. Below is a minimal example of how I am doing this locally. How could I run this code in a Google Cloud Function without needing to upload the service account credentials to the 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));
});
1
You are misunderstanding how credentials work in Google Cloud. The environment variable is just one method and is typically used for "developer code". Review ADC so that you understand the process that Google libraries use to locate credentials. When writing code for executing in the cloud, typically you want to use the service account credentials assigned to the service and not a service account JSON file. In your answer you are using ADC to locate credentials. Understanding this process is important to creating reliable, deployable code cloud.google.com/docs/authentication/productionJohn Hanley

1 Answers

3
votes

I managed to find a solution to this in the readme.md of the googleapis nodejs github repo. To solve my problem I used:


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));
}