1

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

Darshan Naik
  • 271
  • 1
  • 4
  • 15

2 Answers2

2

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.

pessolato
  • 1,472
  • 6
  • 14
  • 1
    Check the documentation also ;) – guillaume blaquiere Aug 21 '19 at 19:30
  • Sorry, probably I was not clear with the question. I have a user logged in via firebase, every time they log in, I get their id_token, how can I connect my firebase user to GCP cloud functions has an authenticated user so that I can invoke CF?@gu – Darshan Naik Oct 28 '19 at 18:15
  • @guillaumeblaquiere, I saw this ans of yours [https://stackoverflow.com/questions/58245338/why-doesnt-granting-allauthenticatedusers-member-the-cloud-functions-invoker/58248009#58248009] – Darshan Naik Oct 28 '19 at 18:21
  • @mj21 Can you help me with this? – Darshan Naik Oct 29 '19 at 11:14
0

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

Siddharth Sachdeva
  • 1,812
  • 1
  • 20
  • 29