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

Geo*_*rge 5 google-app-engine authorization node.js google-cloud-functions

我在 Google Cloud 上的 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
      }
    });
Run Code Online (Sandbox Code Playgroud)

Geo*_*rge 7

经过无数个小时的努力,我在自动完成建议中滚动时偶然发现了答案。Google 有有关身份验证的文档,但没有提到 Cloud Functions 发出 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
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您需要定义 GOOGLE_APPLICATION_CREDENTIALS 环境变量才能使其工作。另外,我必须给构造函数 `const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/cloud-platform'});` 提供一个显式的范围字符串,否则您会得到以下内容.getAccessToken(): 400 错误请求 `{ error: 'invalid_scope', error_description: '提供的 OAuth 范围或 ID 令牌受众无效。' }` (2认同)