com.google.api.client.auth.oauth2.TokenRequest Java Examples

The following examples show how to use com.google.api.client.auth.oauth2.TokenRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 5 votes vote down vote up
private String getServiceAccountToken(ServiceAccountCredentials credential, String targetAudience)
    throws IOException, GeneralSecurityException {
  log.debug("Fetching service account id token for {}", credential.getAccount());
  final TokenRequest request = new TokenRequest(
      this.httpTransport, JSON_FACTORY,
      new GenericUrl(credential.getTokenServerUri()),
      "urn:ietf:params:oauth:grant-type:jwt-bearer");
  final Header header = jwtHeader();
  final Payload payload = jwtPayload(
      targetAudience, credential.getAccount(), credential.getTokenServerUri().toString());
  request.put("assertion", JsonWebSignature.signUsingRsaSha256(
      credential.getPrivateKey(), JSON_FACTORY, header, payload));
  final TokenResponse response = request.execute();
  return (String) response.get("id_token");
}
 
Example #2
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 5 votes vote down vote up
private String getServiceAccountIdTokenUsingAccessToken(GoogleCredentials credentials,
                                                        String serviceAccount, String targetAudience)
    throws IOException {
  final String tokenServerUrl = "https://oauth2.googleapis.com/token";
  final Header header = jwtHeader();
  final JsonWebToken.Payload payload = jwtPayload(
      targetAudience, serviceAccount, tokenServerUrl);
  final Iam iam = new Iam.Builder(httpTransport, JSON_FACTORY,
      new HttpCredentialsAdapter(withScopes(credentials, IamScopes.all()))).build();
  final String content = Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(header)) + "."
                         + Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(payload));
  byte[] contentBytes = StringUtils.getBytesUtf8(content);
  final SignBlobResponse signResponse;
  try {
    signResponse = iam.projects().serviceAccounts()
        .signBlob("projects/-/serviceAccounts/" + serviceAccount, new SignBlobRequest()
            .encodeBytesToSign(contentBytes))
        .execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == 403) {
      throw new IOException(
          "Unable to sign request for id token, missing Service Account Token Creator role for self on "
          + serviceAccount + " or IAM api not enabled?", e);
    }
    throw e;
  }
  final String assertion = content + "." + signResponse.getSignature();
  final TokenRequest request = new TokenRequest(
      httpTransport, JSON_FACTORY,
      new GenericUrl(tokenServerUrl),
      "urn:ietf:params:oauth:grant-type:jwt-bearer");
  request.put("assertion", assertion);
  final TokenResponse tokenResponse = request.execute();
  return (String) tokenResponse.get("id_token");
}
 
Example #3
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 5 votes vote down vote up
private String getUserToken(UserCredentials credentials) throws IOException {
  log.debug("Fetching user id token");
  final TokenRequest request = new RefreshTokenRequest(
      this.httpTransport, JSON_FACTORY,
      new GenericUrl(credentials.toBuilder().getTokenServerUri()),
      credentials.getRefreshToken())
      .setClientAuthentication(new ClientParametersAuthentication(
          credentials.getClientId(), credentials.getClientSecret()))
      .setRequestInitializer(new HttpCredentialsAdapter(credentials));
  final TokenResponse response = request.execute();
  return (String) response.get("id_token");
}
 
Example #4
Source File: CredentialFactory.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Override
protected TokenResponse executeRefreshToken() throws IOException {
  if (getServiceAccountPrivateKey() == null) {
    return super.executeRefreshToken();
  }
  // service accounts: no refresh token; instead use private key to request new access token
  JsonWebSignature.Header header =
      new JsonWebSignature.Header()
          .setAlgorithm("RS256")
          .setType("JWT")
          .setKeyId(getServiceAccountPrivateKeyId());

  long currentTime = getClock().currentTimeMillis();
  JsonWebToken.Payload payload =
      new JsonWebToken.Payload()
          .setIssuer(getServiceAccountId())
          .setAudience(getTokenServerEncodedUrl())
          .setIssuedAtTimeSeconds(currentTime / 1000)
          .setExpirationTimeSeconds(currentTime / 1000 + DEFAULT_TOKEN_EXPIRATION_SECONDS)
          .setSubject(getServiceAccountUser());
  payload.put("scope", WHITESPACE_JOINER.join(getServiceAccountScopes()));

  try {
    String assertion =
        JsonWebSignature.signUsingRsaSha256(
            getServiceAccountPrivateKey(), getJsonFactory(), header, payload);
    TokenRequest request =
        new TokenRequest(
                getTransport(),
                getJsonFactory(),
                new GenericUrl(getTokenServerEncodedUrl()),
                "urn:ietf:params:oauth:grant-type:jwt-bearer")
            .setRequestInitializer(getRequestInitializer());
    request.put("assertion", assertion);
    return request.execute();
  } catch (GeneralSecurityException e) {
    throw new IOException("Failed to refresh token", e);
  }
}
 
Example #5
Source File: GoogleCredential.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
@Beta
protected TokenResponse executeRefreshToken() throws IOException {
  if (serviceAccountPrivateKey == null) {
    return super.executeRefreshToken();
  }
  // service accounts: no refresh token; instead use private key to request new access token
  JsonWebSignature.Header header = new JsonWebSignature.Header();
  header.setAlgorithm("RS256");
  header.setType("JWT");
  header.setKeyId(serviceAccountPrivateKeyId);
  JsonWebToken.Payload payload = new JsonWebToken.Payload();
  long currentTime = getClock().currentTimeMillis();
  payload.setIssuer(serviceAccountId);
  payload.setAudience(getTokenServerEncodedUrl());
  payload.setIssuedAtTimeSeconds(currentTime / 1000);
  payload.setExpirationTimeSeconds(currentTime / 1000 + 3600);
  payload.setSubject(serviceAccountUser);
  payload.put("scope", Joiner.on(' ').join(serviceAccountScopes));
  try {
    String assertion = JsonWebSignature.signUsingRsaSha256(
        serviceAccountPrivateKey, getJsonFactory(), header, payload);
    TokenRequest request = new TokenRequest(
        getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()),
        "urn:ietf:params:oauth:grant-type:jwt-bearer");
    request.put("assertion", assertion);
    return request.execute();
  } catch (GeneralSecurityException exception) {
    IOException e = new IOException();
    e.initCause(exception);
    throw e;
  }
}
 
Example #6
Source File: ManagedServiceAccountKeyCredential.java    From styx with Apache License 2.0 4 votes vote down vote up
private TokenResponse requestToken(String signedJwt) throws IOException {
  var tokenRequest = new TokenRequest(Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
      new GenericUrl(getTokenServerEncodedUrl()), "urn:ietf:params:oauth:grant-type:jwt-bearer");
  tokenRequest.put("assertion", signedJwt);
  return tokenRequest.execute();
}
 
Example #7
Source File: IdTokenResponse.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Executes the given ID token request, and returns the parsed ID token response.
 *
 * @param tokenRequest token request
 * @return parsed successful ID token response
 * @throws TokenResponseException for an error response
 */
public static IdTokenResponse execute(TokenRequest tokenRequest) throws IOException {
  return tokenRequest.executeUnparsed().parseAs(IdTokenResponse.class);
}