Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Last active July 20, 2019 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salrashid123/673ea364f923e515d4e01bcbe9acc680 to your computer and use it in GitHub Desktop.
Save salrashid123/673ea364f923e515d4e01bcbe9acc680 to your computer and use it in GitHub Desktop.
GoogleID Token with Google api client library
package com.test;
import java.util.Arrays;
import java.io.FileInputStream;
import java.io.File;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iamcredentials.v1.IAMCredentials;
import com.google.api.services.iamcredentials.v1.IAMCredentialsScopes;
import com.google.api.services.iamcredentials.v1.model.GenerateIdTokenRequest;
import com.google.api.services.iamcredentials.v1.model.GenerateIdTokenResponse;
/*
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-iamcredentials</artifactId>
<version>v1-rev46-1.25.0</version>
</dependency>
*/
public class TestApp {
public static void main(String[] args) {
TestApp tc = new TestApp();
}
public TestApp() {
try
{
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
// export GOOGLE_APPLICATION_CREDENTIALS=/path/to/svc.json
//GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport,jsonFactory);
String SERVICE_ACCOUNT_JSON_FILE = "/path/to/svc.json";
FileInputStream inputStream = new FileInputStream(new File(SERVICE_ACCOUNT_JSON_FILE));
GoogleCredential credential = GoogleCredential.fromStream(inputStream, httpTransport, jsonFactory);
if (credential.createScopedRequired())
credential = credential.createScoped(Arrays.asList(IAMCredentialsScopes.CLOUD_PLATFORM));
IAMCredentials service = new IAMCredentials.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("oauth client")
.build();
String name = "projects/-/serviceAccounts/impersonated-account@fabled-ray-104117.iam.gserviceaccount.com";
GenerateIdTokenRequest idreq = new GenerateIdTokenRequest();
idreq.setAudience("https://foo");
GenerateIdTokenResponse idresp = service.projects().serviceAccounts().generateIdToken(name, idreq).execute();
System.out.println(idresp.toPrettyString());
}
catch (Exception ex) {
System.out.println("Error: " + ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment