com.google.api.client.json.webtoken.JsonWebSignature.Header Java Examples

The following examples show how to use com.google.api.client.json.webtoken.JsonWebSignature.Header. 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: GoogleIdTokenVerifierTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testVerify() throws Exception {
  GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(
      new GooglePublicKeysManagerTest.PublicCertsMockHttpTransport(), new JacksonFactory()).build();
  Header header = new Header();
  header.setAlgorithm("RS25");
  Payload payload = newPayload(CLIENT_ID);
  Payload payload2 = newPayload(CLIENT_ID + "2");
  GoogleIdToken idToken = new GoogleIdToken(header, payload, new byte[0], new byte[0]);
  GoogleIdToken idToken2 = new GoogleIdToken(header, payload2, new byte[0], new byte[0]);
  assertFalse(verifier.verify(idToken));
  assertFalse(verifier.verify(idToken2));
  verifier = new GoogleIdTokenVerifier(
      new GooglePublicKeysManagerTest.PublicCertsMockHttpTransport(), new JacksonFactory());
  assertFalse(verifier.verify(idToken));
  assertFalse(verifier.verify(idToken2));
  // TODO(yanivi): add a unit test that returns true
}
 
Example #2
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private String getErrorForTokenWithoutKid(IdToken.Header header, IdToken.Payload payload) {
  if (isCustomToken(payload)) {
    return String.format("%s expects %s, but was given a custom token.",
        method, articledShortName);
  } else if (isLegacyCustomToken(header, payload)) {
    return String.format("%s expects %s, but was given a legacy custom token.",
        method, articledShortName);
  }
  return String.format("Firebase %s has no \"kid\" claim.", shortName);
}
 
Example #3
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 #4
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 #5
Source File: IdTokenVerifierTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
private static IdToken newIdToken(String issuer, String audience) {
  Payload payload = new Payload();
  payload.setIssuer(issuer);
  payload.setAudience(audience);
  payload.setExpirationTimeSeconds(2000L);
  payload.setIssuedAtTimeSeconds(1000L);
  return new IdToken(new Header(), payload, new byte[0], new byte[0]);
}
 
Example #6
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private String getErrorIfContentInvalid(final IdToken idToken) {
  final Header header = idToken.getHeader();
  final Payload payload = idToken.getPayload();

  String errorMessage = null;
  if (header.getKeyId() == null) {
    errorMessage = getErrorForTokenWithoutKid(header, payload);
  } else if (!RS256.equals(header.getAlgorithm())) {
    errorMessage = String.format(
        "Firebase %s has incorrect algorithm. Expected \"%s\" but got \"%s\".",
        shortName,
        RS256,
        header.getAlgorithm());
  } else if (!idToken.verifyAudience(idTokenVerifier.getAudience())) {
    errorMessage = String.format(
        "Firebase %s has incorrect \"aud\" (audience) claim. Expected \"%s\" but got \"%s\". %s",
        shortName,
        joinWithComma(idTokenVerifier.getAudience()),
        joinWithComma(payload.getAudienceAsList()),
        getProjectIdMatchMessage());
  } else if (!idToken.verifyIssuer(idTokenVerifier.getIssuers())) {
    errorMessage = String.format(
        "Firebase %s has incorrect \"iss\" (issuer) claim. Expected \"%s\" but got \"%s\". %s",
        shortName,
        joinWithComma(idTokenVerifier.getIssuers()),
        payload.getIssuer(),
        getProjectIdMatchMessage());
  } else if (payload.getSubject() == null) {
    errorMessage = String.format(
        "Firebase %s has no \"sub\" (subject) claim.",
        shortName);
  } else if (payload.getSubject().isEmpty()) {
    errorMessage = String.format(
        "Firebase %s has an empty string \"sub\" (subject) claim.",
        shortName);
  } else if (payload.getSubject().length() > 128) {
    errorMessage = String.format(
        "Firebase %s has \"sub\" (subject) claim longer than 128 characters.",
        shortName);
  } else if (!verifyTimestamps(idToken)) {
    errorMessage = String.format(
        "Firebase %s has expired or is not yet valid. Get a fresh %s and try again.",
        shortName,
        shortName);
  }

  return errorMessage;
}
 
Example #7
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private boolean isLegacyCustomToken(IdToken.Header header, IdToken.Payload payload) {
  return "HS256".equals(header.getAlgorithm())
      && new BigDecimal(0).equals(payload.get("v"))
      && containsLegacyUidField(payload);
}
 
Example #8
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 4 votes vote down vote up
private static Header jwtHeader() {
  final Header header = new Header();
  header.setAlgorithm("RS256");
  header.setType("JWT");
  return header;
}