How does one get the id_token using Google's OAuth2 Java Api?

Viewed 536

I'm trying to get my head around the OAuth2 Java library that Google provides.

I have everything I need to make the request to Google's token endpoint manually using Springs built-in WebClient. However, this is very verbose and feels like re-inventing the wheel. It got me thinking that there must be a way to get this data using the classes provided by the library. Right?

Currently I am using the com.google.auth.oauth2.UserAuthorizer class to build up a request for the exchange of information.

val userCredentials: UserCredentials = UserAuthorizer.newBuilder()
  .setClientId(googleOauthConfig.clientId)
  .setTokenStore(tokenStore)
  .setScopes(googleOauthConfig.scopes)
  .setTokenServerUri(URI.create("https://oauth2.googleapis.com/token"))
  .setCallbackUri(redirectUri)
  .build()
  .getCredentialsFromCode(authorizationCode, redirectUri)

The internals of getCredentialsFromCode() parses the response and it contains all the tokens. Including the id_token but, it gets discarded when constructing the UserCredentials object further down.

Debug mode showing that the value for id_token is stored

return UserCredentials.newBuilder()
  .setClientId(clientId.getClientId())
  .setClientSecret(clientId.getClientSecret())
  .setRefreshToken(refreshToken)
  .setAccessToken(accessToken)
  .setHttpTransportFactory(transportFactory)
  .setTokenServerUri(tokenServerUri)
  .build(); // no mention of id_token

Regardless, I want to get this value so I can know basic information about the user such as their name, birthday and email address from a single request.

There does exist a method called idTokenWithAudience() which returns a Google ID Token from the refresh token response. If I call this, I get a token back that doesn't contain all the data that was available in the identically named id_token mentioned earlier making it a no-go either.

1 Answers

You can use IdTokenCredentials to access the ID token like so:

var credentials = UserCredentials.newBuilder()
        .setClientId("...")
        .setClientSecret("...")
        .setRefreshToken("...")
        .build()
        .createScoped("openid email");

var idToken = IdTokenCredentials
        .newBuilder()
        .setIdTokenProvider((IdTokenProvider)credentials)
        .build();

idToken.refresh();
System.out.println(idToken.getIdToken().getTokenValue());
Related