3

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
  • 2,762
  • 1
  • 20
  • 49
  • Why not use the service account locally too? Then, rather than trying to ride your `gcloud` credentials, you can use the same flow locally as you're using on GKE. – DazWilkin Jul 28 '19 at 04:47
  • I am doing that now. I’m trying to determine if user account creds is also an option. – jacob Jul 28 '19 at 12:03
  • Got it. I did a brief search, found Google's oauth2l but I think you'll have to reimplement the web-based flow to take your user account and generate the JWT for the identity token. – DazWilkin Jul 28 '19 at 14:14
  • Or `child_process` make the `gcloud` call and process the result – DazWilkin Jul 28 '19 at 14:42
  • Hmmm: https://github.com/googleapis/google-auth-library-nodejs#choosing-the-correct-credential-type-automatically – DazWilkin Jul 28 '19 at 19:24
  • @jacob did find a solution? I am also trying to call a CF from one of our node js applications we have in our GKE cluster, I am still not sure how I can get the identity token of our service account. – Soumitri Pattnaik Dec 21 '20 at 17:49
  • @SoumitriPattnaik The solution is the second code block in my question above. – jacob Dec 21 '20 at 21:06

0 Answers0