如何在 Node.JS Google 云函数中获取访问令牌?

How do I get access token inside Node.JS Google Cloud function?

我在 Google 云上的 Node.JS 中有一个云函数,我需要向 Google 发出 GET 请求,它需要一个授权令牌。使用 curl 您可以使用 $(gcloud auth application-default print-access-token) 生成一个。但这在云实例中不起作用,所以我如何生成一个?

部分功能:

exports.postTestResultsToSlack = functions.testLab
  .testMatrix()
  .onComplete(async testMatrix => {

    if (testMatrix.clientInfo.details['testType'] != 'regression') {
      // Not regression tests
      return null;
    }

    const { testMatrixId, outcomeSummary, resultStorage } = testMatrix;

    const projectID = "project-feat1"
    const executionID = resultStorage.toolResultsExecutionId
    const historyID = resultStorage.toolResultsHistoryId

    const historyRequest = await axios.get(`https://toolresults.googleapis.com/toolresults/v1beta3/projects/${projectID}/histories/${historyID}/executions/${executionID}/environments`, {
      headers: {
        'Authorization': `Bearer $(gcloud auth application-default print-access-token)`,
        'X-Goog-User-Project': projectID
      }
    });

在花费了无数个小时之后,我偶然发现了滚动自动完成建议的答案。 Google 有关于身份验证的文档,但 none 提到云功能需要什么才能发出 API 请求:

const {GoogleAuth} = require('google-auth-library');

const auth = new GoogleAuth();
const token = await auth.getAccessToken()

const historyRequest = await axios.get(
`https://toolresults.googleapis.com/toolresults/v1beta3/projects/${projectID}/histories/${historyID}/executions/${executionID}/environments`, 
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'X-Goog-User-Project': projectID
        }
    });