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

z0qdvdin  于 11个月前  发布在  Node.js
关注(0)|答案(3)|浏览(111)

我在Google Cloud上的Node.JS中有一个cloud函数,我需要向Google发出GET请求,它需要一个auth token。使用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
      }
    });

字符串

4smxwvx5

4smxwvx51#

经过无数个小时的花费,我偶然发现了答案滚动通过自动完成的建议.谷歌有关于身份验证的文档,但没有提到这是什么你需要云函数使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
        }
    });

字符串

jgwigjjp

jgwigjjp2#

这是我为google auth编写的最后一段代码,与上面的代码类似,但是使用了一个base64的环境变量credentials。

import {GoogleAuth} from 'google-auth-library';

function getGoogleCredentials() {
  const base64Data = process.env.BASE_64_CREDENTIALS!
  // Convert the base64 string back to a Buffer
  const bufferData = Buffer.from(base64Data, 'base64');

  // Convert the Buffer back to a JSON string
  const jsonData = bufferData.toString('utf-8');

  // Parse the JSON string to get the JavaScript object
  const jsonObject = JSON.parse(jsonData);
  return {
    private_key: jsonObject.private_key,
    client_email: jsonObject.client_email
  }
}

const auth = new GoogleAuth({
  scopes: "https://www.googleapis.com/auth/cloud-platform",
  credentials: getGoogleCredentials()
});
const token = await auth.getAccessToken()

字符串
我一辈子都无法理解谷歌如何期望人们使用任何一种自动部署软件来做不同的事情。

xtfmy6hx

xtfmy6hx3#

我遇到了同样的问题,但调用谷歌翻译API,创建一个令牌,你需要添加范围,如果你使用的是服务帐户,授予服务使用消费者角色。

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

const auth = new GoogleAuth({
  scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
const token = await auth.getAccessToken()

const body = {sourceLanguageCode: 'en',targetLanguageCode: 'ru',contents: ['Dr. Watson, come here!', 'Bring me some coffee!'],};

const request = await axios.post('https://translation.googleapis.com/v3/projects/[project-id]:translateText', body, {
    headers: { Authorization: `Bearer ${token}`, 'x-goog-user-project': '[project-id]' },
  })

字符串

相关问题