title: Generate bearer token for google cloud function - Java
body: <p>I'm trying to connect to cloud function such as https://us-west1-&lt;&gt;.cloudfunctions.net from java, and I'm trying to generate the bearer token for this function using a code as follows:</p>
  <pre><code>String audience = https://&lt;projectname&gt;-&lt;region&gt;-&lt;projectid&gt;.cloudfunctions.net/&lt;myFunction&gt;;
  
  GoogleCredentials credentials = GoogleCredentials
                  .getApplicationDefault()
                  .createScoped(Arrays.asList(&quot;https://www.googleapis.com/auth/cloud-platform&quot;));
  
  IdTokenCredentials tokenCredential =
                  IdTokenCredentials.newBuilder()
                      .setIdTokenProvider((IdTokenProvider) credentials)
                      .setTargetAudience(audience)
                      .build();
          
  tokenCredential.refresh();
          
  String token = tokenCredential.getIdToken().getTokenValue();
  </code></pre>
  <p>When I run the application the token is generated. But if I take the token and put this on postman, the server returns an 401 error: <strong>401 Unauthorized</strong>.</p>
  <p>if I use the GCP command &quot;gcloud auth print-identity-token&quot; in GCP cloud shell terminal and use this token in postman, the cloud function invocation is successful.</p>
  <p>The Json file used to get the credentials is similar to this:</p>
  <pre><code>{
    &quot;type&quot;: &quot;service_account&quot;,
    &quot;project_id&quot;: &quot;&lt;project_id&gt;&quot;,
    &quot;private_key_id&quot;: &quot;&lt;private_key_id&gt;&quot;,
    &quot;private_key&quot;: &quot;-----BEGIN PRIVATE KEY----------END PRIVATE KEY-----\n&quot;,
    &quot;client_email&quot;: &quot;aaa@&lt;project_id&gt;.iam.gserviceaccount.com&quot;,
    &quot;client_id&quot;: &quot;&lt;client_id&gt;&quot;,
    &quot;auth_uri&quot;: &quot;https://accounts.google.com/o/oauth2/auth&quot;,
    &quot;token_uri&quot;: &quot;https://oauth2.googleapis.com/token&quot;,
    &quot;auth_provider_x509_cert_url&quot;: &quot;https://www.googleapis.com/oauth2/v1/certs&quot;,
    &quot;client_x509_cert_url&quot;: &quot;https://www.googleapis.com/robot/v1/metadata/x509/&lt;principle&gt;&quot;
  }
  </code></pre>
  <p>Please help me in figuring out how to generate a bearer token in java to invoke a google cloud function.</p>
  <p>Thanks</p>