ServiceAccountProvider extends AbstractProvider { @Override public AccessToken getAccessToken(String googleIdentity, List<String> scopes) { if (! googleIdentity.endsWith(".iam.gserviceaccount.com")) { throw new IllegalArgumentException("Google identity `" + googleIdentity + "` is not a service account"); } try { GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.create(credentials, googleIdentity, null, scopes, 3600); com.google.auth.oauth2.AccessToken token = impersonatedCredentials.refreshAccessToken(); return new AccessToken(token.getTokenValue(), token.getExpirationTime().getTime()); } catch (IOException e) { throw Status.PERMISSION_DENIED.asRuntimeException(); } }  @Override AccessToken getAccessToken(String googleIdentity, List<String> scopes);  }
@Test public void testSuccess() { ServiceAccountProvider provider = new ServiceAccountProvider(); KerberosUserMapper mapper = new KerberosUserMapper(); AccessToken accessToken = provider.getAccessToken(mapper.map("alice@EXAMPLE.COM"), SCOPES); assertTrue(accessToken.getValue().startsWith("y")); assertEquals(2, CharMatcher.is('.').countIn(accessToken.getValue())); assertTrue(accessToken.getExpiresAt() > 0); }
@Test public void testUnauthorized() { ServiceAccountProvider provider = new ServiceAccountProvider(); KerberosUserMapper mapper = new KerberosUserMapper(); try { provider.getAccessToken(mapper.map("bob@EXAMPLE.COM"), SCOPES); fail("StatusRuntimeException not thrown"); } catch (StatusRuntimeException e) { assertEquals(Status.PERMISSION_DENIED.getCode(), e.getStatus().getCode()); } }