Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

access authenticated cloud run form nodejs (this is deployed in cloud run)

I have some question on cloud run 
if we need to access  cloud run of backend(allow  only authenticated)  from another cloud run of nodejs 
do we need service account keys to communicate with authenticated cloud run?
if  can we also do communication between the authenticated cloud run then suggest solution?

cloud run have same service account.

code i am using in nodejs

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

async function request() {
  console.info(`request ${url} with target audience ${targetAudience}`);
  const client = await auth.getIdTokenClient(targetAudience);

  // Alternatively, one can use `client.idTokenProvider.fetchIdToken`
  // to return the ID Token.
  const res = await client.request({url});
  console.info(res.data);
}

request().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});
0 1 178
1 REPLY 1

Hi @mhvharsha,

It looks like you’re intending to set up a service-to-service communication between your two Cloud Run services, so in that case, there’s no need for service account keys as they are only appropriate when you need to authenticate from outside Google Cloud.

You just simply need to set up a service account with a Cloud Run Invoker role attached to the receiving service through the Google Cloud console or CLI.

Let’s call the calling service (Cloud Run A) and the receiving service (Cloud Run B), then assume Cloud Run B has the URL: “https://my-cloud-run-service.run.app”.

With the help of the steps below, the way for both services to communicate can be achieved:

  1. Setup a Service Account - Configure Cloud Run B by adding a principal that goes by default with: PROJECT_NUMBER-compute@developer.gserviceaccount.com. Then make sure you grant it with a role “Cloud Run Invoker”.
  2. The code you mentioned in the post can be written for Cloud Run A. Just make sure the following lines are added above const {GoogleAuth} = require('google-auth-library');

 

// It can be a subfolder within a Cloud Run URL
const targetUrl = 'https://my-cloud-run-service.run.app'; 

const targetAudience = 'https://my-cloud-run-service.run.app';

 

In step 2, note that setting up a const targetAudience variable points to the URL of Cloud Run B. You can set up the targetUrl variable to be the same as the targetAudience variable. Otherwise, if it’s a specific sub-directory/sub-folder within the receiving service’s URL then it can be something like: “https://my-cloud-run-service.run.app/books/delete/12345

Was this helpful? If so, please accept this answer as “Solution”. If you need additional assistance, reply here within 2 business days and I’ll be happy to help.