com.google.api.client.json.webtoken.JsonWebToken Java Examples

The following examples show how to use com.google.api.client.json.webtoken.JsonWebToken. 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: VerifyIapRequestHeader.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private boolean verifyJwt(String jwtToken, String expectedAudience) {
  TokenVerifier tokenVerifier = TokenVerifier.newBuilder()
      .setAudience(expectedAudience)
      .setIssuer(IAP_ISSUER_URL)
      .build();
  try {
    JsonWebToken jsonWebToken = tokenVerifier.verify(jwtToken);

    // Verify that the token contain subject and email claims
    JsonWebToken.Payload payload = jsonWebToken.getPayload();
    return payload.getSubject() != null && payload.get("email") != null;
  } catch (TokenVerifier.VerificationException e) {
    System.out.println(e.getMessage());
    return false;
  }
}
 
Example #2
Source File: TestCertificates.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public static JsonWebSignature getJsonWebSignature() throws IOException {
  if (jsonWebSignature == null) {
    JsonWebSignature.Header header = new JsonWebSignature.Header();
    header.setAlgorithm("RS256");
    List<String> certificates = Lists.newArrayList();
    certificates.add(FOO_BAR_COM_CERT.getBase64Der());
    certificates.add(CA_CERT.getBase64Der());
    header.setX509Certificates(certificates);
    JsonWebToken.Payload payload = new JsonWebToken.Payload();
    payload.set("foo", "bar");
    int firstDot = JWS_SIGNATURE.indexOf('.');
    int secondDot = JWS_SIGNATURE.indexOf('.', firstDot + 1);
    byte[] signatureBytes = Base64.decodeBase64(JWS_SIGNATURE.substring(secondDot + 1));
    byte[] signedContentBytes = StringUtils.getBytesUtf8(JWS_SIGNATURE.substring(0, secondDot));
    JsonWebSignature signature =
        new JsonWebSignature(header, payload, signatureBytes, signedContentBytes);
    jsonWebSignature = signature;
  }
  return jsonWebSignature;
}
 
Example #3
Source File: TestTokenFactory.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public String createToken(JsonWebSignature.Header header, JsonWebToken.Payload payload) {
  try {
    return JsonWebSignature.signUsingRsaSha256(privateKey, JSON_FACTORY, header, payload);
  } catch (GeneralSecurityException | IOException e) {
    throw new RuntimeException("Failed to create test token", e);
  }
}
 
Example #4
Source File: TestTokenFactory.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public JsonWebToken.Payload createTokenPayload() {
  JsonWebToken.Payload payload = new JsonWebToken.Payload();
  payload.setIssuer(issuer);
  payload.setAudience(PROJECT_ID);
  payload.setIssuedAtTimeSeconds(CLOCK.currentTimeMillis() / 1000);
  payload.setExpirationTimeSeconds(CLOCK.currentTimeMillis() / 1000 + 3600);
  payload.setSubject(UID);
  return payload;
}
 
Example #5
Source File: ServiceAccountAccessTokenProvider.java    From curiostack with MIT License 5 votes vote down vote up
private String createAssertion(Type type, long currentTimeMillis) {
  JsonWebSignature.Header header = new JsonWebSignature.Header();
  header.setAlgorithm("RS256");
  header.setType("JWT");
  header.setKeyId(credentials.getPrivateKeyId());

  long currentTimeSecs = TimeUnit.MILLISECONDS.toSeconds(currentTimeMillis);

  JsonWebToken.Payload payload = new JsonWebToken.Payload();

  String serviceAccount =
      MoreObjects.firstNonNull(credentials.getServiceAccountUser(), credentials.getClientEmail());

  payload.setIssuer(serviceAccount);
  payload.setAudience(AUDIENCE);
  payload.setIssuedAtTimeSeconds(currentTimeSecs);
  payload.setExpirationTimeSeconds(currentTimeSecs + 3600);
  payload.setSubject(serviceAccount);
  payload.put(
      "scope",
      type == Type.ID_TOKEN
          ? credentials.getClientEmail()
          : String.join(" ", credentials.getScopes()));

  String assertion;
  try {
    assertion =
        JsonWebSignature.signUsingRsaSha256(
            credentials.getPrivateKey(), JacksonFactory.getDefaultInstance(), header, payload);
  } catch (GeneralSecurityException | IOException e) {
    throw new IllegalStateException(
        "Error signing service account access token request with private key.", e);
  }
  return assertion;
}
 
Example #6
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 #7
Source File: ManagedServiceAccountKeyCredential.java    From styx with Apache License 2.0 5 votes vote down vote up
private JsonWebToken.Payload jwtPayload() {
  var currentTime = System.currentTimeMillis();
  var payload = new JsonWebToken.Payload();
  payload.setIssuer(getServiceAccountId());
  payload.setAudience(getTokenServerEncodedUrl());
  payload.setIssuedAtTimeSeconds(currentTime / 1000);
  payload.setExpirationTimeSeconds(currentTime / 1000 + 3600);
  payload.setSubject(getServiceAccountUser());
  payload.put("scope", Joiner.on(' ').join(getServiceAccountScopes()));
  return payload;
}
 
Example #8
Source File: ManagedServiceAccountKeyCredential.java    From styx with Apache License 2.0 5 votes vote down vote up
private String signJwt(String serviceAccount, JsonWebToken.Payload payload) throws IOException {
  var fullServiceAccountName = "projects/-/serviceAccounts/" + serviceAccount;
  var request = new SignJwtRequest()
      .setPayload(Utils.getDefaultJsonFactory().toString(payload));
  return iam.projects().serviceAccounts()
      .signJwt(fullServiceAccountName, request)
      .execute()
      .getSignedJwt();
}
 
Example #9
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 #10
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;
  }
}