0
votes

On GCP cloud functions if I unchecked the "Allow unauthenticated invocations", I can access the HTTP API only via an access token provided gcloud auth print-access-token command, which is a JWT token, how can I get similar access token via postman, so that my mobile app can get similar token and be able to invoke cloud function? Should I set up my own OAuth server which is on GCP, if yes how?

PS: Please refer this question here

2

2 Answers

2
votes

This should do the trick:

curl -i https://[REGION]-[PROJECT_ID].cloudfunctions.net/[FUNCTION_NAME] -H "Authorization: bearer $(gcloud auth print-identity-token)"

I also suggest checking the Authenticating Developers, Functions, and End-users documentation for more ways to authenticate with Google Cloud Functions.

0
votes

That's how you can generate the token programmatically -

// const url = 'https://TARGET_URL';
const {GoogleAuth} = require('google-auth-library');
const auth = new GoogleAuth();

async function request() {
  if (!targetAudience) {
    // Use the request URL hostname as the target audience for requests.
    const {URL} = require('url');
    targetAudience = new URL(url).origin;
  }
  console.info(`request ${url} with target audience ${targetAudience}`);
  const client = await auth.getIdTokenClient(targetAudience);
  const res = await client.request({url});
  console.info(res.data);
}

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

Once token is generated you can pass it in header as -

Authorization: Bearer ${myToken}

Read further documentations here - https://cloud.google.com/functions/docs/securing/authenticating#functions-bearer-token-example-nodejs