Google Cloud Platform - cloud functions API - 401 Unauthorized

you have to know (and it's not clear again) that you need an access token to call Google Cloud API, but an identity token to call IAP (on App Engine for example) or private Cloud Function and Cloud Run. And this identity token needs to be signed by Google.

Google Cloud Platform - cloud functions API - 401 Unauthorized

you have to know (and it's not clear again) that you need an access token to call Google Cloud API, but an identity token to call IAP (on App Engine for example) or private Cloud Function and Cloud Run. And this identity token needs to be signed by Google.

And, as mentioned in the code, you need to have a service account on your computer, but I recommend you avoid this on GCP, it's not required if you use default authentication (see my code, on your computer set the GOOGLE_APPLICATION_CREDENTIALS env var that points to the service account key file). The best way is to not use the service account key file on your computer also, but it's not yet possible (that is a security issue IMO, and I'm discussing with Google on this...)

Anyway, here is a code snippet that works in Java (nowhere in the documentation...)

  String myUri = "https://path/to/url";
  // You can use here your service account key file. But, on GCP you don't require a service account key file.
  // However, on your computer, you require one because you need and identity token and you can generate it with your user account (long story... I'm still in discussion with Google about this point...)
  Credentials credentials = GoogleCredentials.getApplicationDefault().createScoped("https://www.googleapis.com/auth/cloud-platform");
  IdTokenCredentials idTokenCredentials = IdTokenCredentials.newBuilder()
    .setIdTokenProvider((IdTokenProvider) credentials)
    .setTargetAudience(myUri).build();

  HttpRequestFactory factory = new NetHttpTransport().createRequestFactory(new HttpCredentialsAdapter(idTokenCredentials));

  HttpRequest request = factory.buildGetRequest(new GenericUrl(myUri));
  HttpResponse httpResponse = request.execute();
  System.out.println(CharStreams.toString(new InputStreamReader(httpResponse.getContent(), Charsets.UTF_8)));

NOTE If you want to continue to use the RestTemplate object and set manually your token, you can generate it like this

  String token = ((IdTokenProvider) credentials).idTokenWithAudience(myUri, Collections.EMPTY_LIST).getTokenValue();
  System.out.println(token);