Home > Enterprise >  What's the equivalent of auth.getIdTokenClient() on Android?
What's the equivalent of auth.getIdTokenClient() on Android?

Time:04-22

I need to query a token from a GCP function, for that, I want to do what the js function GoogleAuth<JSONClient>.getIdTokenClient(targetAudience) does but on Android.

Right now I'm using this code to generate an auth token:

GoogleCredentials
                .fromStream(
                    app.assets.open("my_config_file.json")
                )
                .createScoped(
                    listOf(
                        "https://www.googleapis.com/auth/cloud-platform"
                    )
                )

But the token generated is a ya29.c., wherewith the getIdToken I get a valid token.

How can I get a valid token as getIdToken on my Android app?

CodePudding user response:

For Java based applications you have the google-auth-library-java. Looking in the docs for this library you have the IdTokenCredentials.Builder and IdTokenCredentials classes.

Also you have an example use case:

 String credPath = "/path/to/svc_account.json";
 String targetAudience = "https://example.com";
 // For Application Default Credentials (as ServiceAccountCredentials)
 // export GOOGLE_APPLICATION_CREDENTIALS=/path/to/svc.json
 GoogleCredentials adcCreds = GoogleCredentials.getApplicationDefault();
 if (!adcCreds instanceof IdTokenProvider) {
   // handle error message
 }

 IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder()
     .setIdTokenProvider(adcCreds)
     .setTargetAudience(targetAudience).build();

 // Use the IdTokenCredential in an authorized transport
 GenericUrl genericUrl = new GenericUrl("https://example.com");
 HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(tokenCredential);
 HttpTransport transport = new NetHttpTransport();
 HttpRequest request = transport.createRequestFactory(adapter).buildGetRequest(genericUrl);
 HttpResponse response = request.execute();

 // Print the token, expiration and the audience
 System.out.println(tokenCredential.getIdToken().getTokenValue());
 System.out.println(tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudienceAsList());
 System.out.println(tokenCredential.getIdToken().getJsonWebSignature().getPayload().getExpirationTimeSeconds());
Documentation:
  • Related