Last active
July 20, 2019 18:22
-
-
Save salrashid123/673ea364f923e515d4e01bcbe9acc680 to your computer and use it in GitHub Desktop.
GoogleID Token with Google api client library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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