'Generate bearer token for cloud function consumption GCP -Java

I'm trying to connect to cloud function such as https://us-central1-<>.cloudfunctions.net from java, and I'm trying to generate the bearer token for this function using a code as follows:

    GoogleCredential credential =
    GoogleCredential.fromStream(new FileInputStream("credentials.json"));
    PrivateKey privateKey = credential.getServiceAccountPrivateKey();
    String privateKeyId = credential.getServiceAccountPrivateKeyId();
           
    System.out.println("privateKeyId " + privateKeyId);
            
    long now = System.currentTimeMillis();
    var iat = new Date(now);
    var exp = new Date(now + 3600 * 1000L);
            
    LinkedHashMap<String, Object> myObject = new LinkedHashMap<String, Object>();
            
    myObject.put("iss", "https://accounts.google.com");
    myObject.put("azp", "[email protected]");
    myObject.put("aud", "https://www.googleapis.com/oauth2/v4/token");
    myObject.put("sub", client_id);
    myObject.put("email", "[email protected]");
    myObject.put("email_verified", true);
            
    LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("alg", "RS256");
    map.put("kid", privateKeyId);
    map.put("typ", "JWT");
            
try {
                Algorithm algorithm = Algorithm.RSA256(null, (RSAPrivateKey) privateKey);
                String signedJwt = JWT.create()
                    .withHeader(map)
                    .withPayload(myObject)
                    .withExpiresAt(exp)
                    .withIssuedAt(iat)
                    .sign(algorithm);
                
                System.out.println("signedJwt: " + signedJwt);
            }    
            catch(JWTCreationException | IllegalArgumentException ex){
                System.out.println(ex);
            }

When I run the application the token is generated: eyJraWQiOiJlNjA3ZWViNTc5ZmExZTkwOGY5NzQyOTRhMTYyZTdjYTUxYTM....

But if I take the token and put this on postman, the server returns an 401 error: 401 Unauthorized.

Finally, if I use the GCP command gcloud auth print-identity-token in CMD and take this token, the consumption is sucessfully.

The Json file used to get the credentials is similar to this:

{
  "type": "service_account",
  "project_id": proyect_id,
  "private_key_id": "e607eeb579fa1e908f974294a162e7ca51axxxxx",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkixxxxxl/HauR+Q==\n-----END PRIVATE KEY-----\n",
  "client_email": "[email protected]",
  "client_id": "1118083965053179xxxx",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/account%appspot.gserviceaccount.com"
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source