node.jsgoogle-app-enginegoogle-cloud-functionsauthorization

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


I have a cloud function in Node.JS on Google Cloud, I need to make GET request to Google and it requires an auth token. Using curl you can generate one using $(gcloud auth application-default print-access-token). But this doesn't work in Cloud instance so how I can generate one?

Some of the function:

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

Solution

  • After countless hours spent, I stumbled across the answer scrolling through auto complete suggestions. Google has documentation about authentication but none mention this what you need for Cloud Functions to make API requests:

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