Summarizing John Hanley's Solution via comment:
There is one item that you must do that the CLI does not need to do. That is to specify the OIDC Identity Token Audience. That value is the URL of the service that you are calling. If you know how to code an HTTP GET Request, reproduce this while executing inside Cloud Functions:
curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=AUDIENCE" \
-H "Metadata-Flavor: Google"
Where AUDIENCE
is the URL of the service you are invoking (i.e. https://TARGET_HOSTNAME/
).
The getIdTokenClient
does not return a Bearer token in the way you are thinking. It returns an OIDC Identity Token which is what you want. Bearer is an HTTP Authentication scheme that supports many different token types. The documentation has examples for you to use.
Example demo code:
'use strict';
function main(
url = 'https://service-1234-uc.a.run.app',
targetAudience = null
) {
if (!targetAudience) {
// Use the target service's hostname as the target audience for requests.
// (For example: https://my-cloud-run-service.run.app)
const {URL} = require('url');
targetAudience = new URL(url).origin;
}
// [START google_auth_idtoken_serverless]
// [START cloudrun_service_to_service_auth]
// [START run_service_to_service_auth]
// [START functions_bearer_token]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// Example: https://my-cloud-run-service.run.app/books/delete/12345
// const url = 'https://TARGET_HOSTNAME/TARGET_URL';
// Example (Cloud Run): https://my-cloud-run-service.run.app/
// Example (Cloud Functions): https://project-region-projectid.cloudfunctions.net/myFunction
// const targetAudience = 'https://TARGET_HOSTNAME/';
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);
const res = await client.request({url});
console.info(res.data);
}
request().catch(err => {
console.error(err.message);
process.exitCode = 1;
});
// [END functions_bearer_token]
// [END run_service_to_service_auth]
// [END cloudrun_service_to_service_auth]
// [END google_auth_idtoken_serverless]
}
const args = process.argv.slice(2);
main(...args);