How to authenticate to Cloud Function using a node.js client

7/25/2019

I have a node.js application running in GKE that needs to be able to make a server-to-server call to a Cloud Function that has permission configured to only allow the service account configured on the GKE pod to invoke it. So basically, the node.js has an environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to the credential key json file mounted on a volume.

Also for local development, it would be nice if it just uses my user account credentials stored with gcloud sdk configuration.

I've figured out how to authentication using a service account credential. Here is the code, assuming the GOOGLE_APPLICATION_CREDENTIALS environment variable contains the path to the credential key json file:

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

    const url = 'https://REGION-PROJECT.cloudfunctions.net/RECEIVING_FUNCTION'
    const auth = new GoogleAuth({
        keyFile: process.env.GOOGLE_APPLICATION_CREDENTIALS,
        clientOptions: {
            additionalClaims: {
                target_audience: url
            }
        }
    })
    const client = await auth.getClient()

    const res = await client.request({ url })
    console.log(res.data)

A slight variation is this way:

import { JWT } from 'google-auth-library'
    const client = new JWT({
        keyFile: process.env.GOOGLE_APPLICATION_CREDENTIALS,
        additionalClaims: {
            target_audience: url
        }
    })

But I'm still not sure how to do this with user account credentials in local development. The closest solution is using cURL:

        curl -i https://REGION-PROJECT.cloudfunctions.net/RECEIVING_FUNCTION \
        -H "Authorization: bearer $(gcloud auth print-identity-token)"

So there is a way, but how do I do it in javascript?

-- jacob
google-auth-library-nodejs
google-cloud-functions
google-cloud-iam
google-cloud-node
google-kubernetes-engine

0 Answers