【问题标题】:How do I get access token inside Node.JS Google Cloud function?如何在 Node.JS Google Cloud 函数中获取访问令牌?
【发布时间】:2021-12-18 22:29:03
【问题描述】:

我在 Google Cloud 上的 Node.JS 中有一个云功能,我需要向 Google 发出 GET 请求,它需要一个身份验证令牌。使用curl,您可以使用$(gcloud auth application-default print-access-token) 生成一个。但这在 Cloud 实例中不起作用,那么我该如何生成呢?

部分功能:

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

【问题讨论】:

  • 您在执行此操作时是否遇到任何错误?如果是这样,你能在这里提供你的错误吗?
  • Error: Request failed with status code 401
  • 查看document 关于使用 Nodejs 以编程方式生成令牌的内容。这个document 谈到了 401 错误及其解决方案。我还发现了一些与您的问题相似的线程,请查看这些线程:Thread1Thread2Thread3
  • 第一个链接坏了。
  • 试试这个:Link

标签: node.js google-app-engine google-cloud-functions authorization


【解决方案1】:

在花费了无数个小时之后,我偶然发现了滚动自动完成建议的答案。 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
        }
    });

【讨论】:

  • 请注意,您需要定义 GOOGLE_APPLICATION_CREDENTIALS 环境变量才能使其工作。此外,我必须为构造函数const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/cloud-platform'}); 提供一个明确的范围字符串,否则您会在 .getAccessToken() 上得到以下信息:400 Bad Request { error: 'invalid_scope', error_description: 'Invalid OAuth scope or ID token audience provided.' }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 2020-06-29
  • 2014-07-08
  • 2012-08-03
  • 2020-10-24
  • 1970-01-01
  • 2015-02-22
相关资源
最近更新 更多