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

The following examples show how to use com.google.api.client.json.webtoken.JsonWebSignature. 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: 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 #2
Source File: GoogleIdTokenVerifierTest.java    From styx with Apache License 2.0 6 votes vote down vote up
private String createToken() throws GeneralSecurityException, IOException {
  var issuedAt = Instant.now().getEpochSecond();
  var expiredAt = issuedAt + 3600; // One hour later
  var payload = new GoogleIdToken.Payload();
  payload.setAuthorizedParty("103411466401044735393");
  payload.setEmail("[email protected]");
  payload.setEmailVerified(true);
  payload.setIssuedAtTimeSeconds(issuedAt);
  payload.setExpirationTimeSeconds(expiredAt);
  payload.setIssuer("https://accounts.google.com");
  payload.setSubject("103411466401044735393");
  GenericJson googleMetadata = new GenericJson()
      .set("compute_engine", new GenericJson()
                                 .set("instance_creation_timestamp", 1556025719L)
                                 .set("instance_id", "5850837338805153689")
                                 .set("instance_name", "gew1-metricscatalogbro-b-b7z2")
                                 .set("project_id", "metrics-catalog")
                                 .set("project_number", 283581591831L)
                                 .set("zone", "europe-west1-d")
      );
  payload.set("google", googleMetadata);

  var header = new JsonWebSignature.Header().setAlgorithm("RS256");
  return JsonWebSignature.signUsingRsaSha256(privateKey, Utils.getDefaultJsonFactory(), header, payload);
}
 
Example #3
Source File: FirebaseTokenFactory.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private String signPayload(JsonWebSignature.Header header,
    FirebaseCustomAuthToken.Payload payload) throws IOException {
  String headerString = Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(header));
  String payloadString = Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(payload));
  String content = headerString + "." + payloadString;
  byte[] contentBytes = StringUtils.getBytesUtf8(content);
  String signature = Base64.encodeBase64URLSafeString(signer.sign(contentBytes));
  return content + "." + signature;
}
 
Example #4
Source File: GoogleIdToken.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the given ID token string and returns the parsed {@link GoogleIdToken}.
 *
 * @param jsonFactory JSON factory
 * @param idTokenString ID token string
 * @return parsed Google ID token
 */
public static GoogleIdToken parse(JsonFactory jsonFactory, String idTokenString)
    throws IOException {
  JsonWebSignature jws =
      JsonWebSignature.parser(jsonFactory).setPayloadClass(Payload.class).parse(idTokenString);
  return new GoogleIdToken(jws.getHeader(), (Payload) jws.getPayload(), jws.getSignatureBytes(),
      jws.getSignedContentBytes());
}
 
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: 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 #7
Source File: PluginTest.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
private String createIdToken(PrivateKey privateKey, Map<String, Object> keyValues) throws Exception {
    JsonWebSignature.Header header = new JsonWebSignature.Header()
        .setAlgorithm("RS256");
    IdToken.Payload payload = new IdToken.Payload()
        .setIssuer("issuer")
        .setSubject(TEST_USER_USERNAME)
        .setAudience(Collections.singletonList("clientId"))
        .setAudience(System.currentTimeMillis() / 60 + 5)
        .setIssuedAtTimeSeconds(System.currentTimeMillis() / 60);
    for(Map.Entry<String, Object> keyValue : keyValues.entrySet()) {
        payload.set(keyValue.getKey(), keyValue.getValue());
    }

    return JsonWebSignature.signUsingRsaSha256(privateKey, JSON_FACORY, header, payload);
}
 
Example #8
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 #9
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 #10
Source File: TestUtils.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public static boolean verifySignature(JsonWebSignature token, List<PublicKey> keys)
    throws Exception {
  for (PublicKey key : keys) {
    if (token.verifySignature(key)) {
      return true;
    }
  }
  return false;
}
 
Example #11
Source File: FirebaseTokenVerifierImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private String createCustomToken() {
  JsonWebSignature.Header header = tokenFactory.createHeader();
  header.setKeyId(null);
  Payload payload = tokenFactory.createTokenPayload();
  payload.setAudience(CUSTOM_TOKEN_AUDIENCE);
  return tokenFactory.createToken(header, payload);
}
 
Example #12
Source File: TestTokenFactory.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public JsonWebSignature.Header createHeader() {
  JsonWebSignature.Header header = new JsonWebSignature.Header();
  header.setAlgorithm("RS256");
  header.setType("JWT");
  header.setKeyId(PRIVATE_KEY_ID);
  return header;
}
 
Example #13
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 #14
Source File: FirebaseCustomAuthToken.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
/** Parses a JWT token string and extracts its headers and payload fields. */
public static FirebaseCustomAuthToken parse(JsonFactory jsonFactory, String tokenString)
    throws IOException {
  JsonWebSignature jws =
      JsonWebSignature.parser(jsonFactory).setPayloadClass(Payload.class).parse(tokenString);
  return new FirebaseCustomAuthToken(
      jws.getHeader(),
      (Payload) jws.getPayload(),
      jws.getSignatureBytes(),
      jws.getSignedContentBytes());
}
 
Example #15
Source File: FirebaseTokenFactory.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public String createSignedCustomAuthTokenForUser(
    String uid, Map<String, Object> developerClaims) throws IOException {
  checkArgument(!Strings.isNullOrEmpty(uid), "Uid must be provided.");
  checkArgument(uid.length() <= 128, "Uid must be shorter than 128 characters.");

  JsonWebSignature.Header header = new JsonWebSignature.Header().setAlgorithm("RS256");

  final long issuedAt = clock.currentTimeMillis() / 1000;
  FirebaseCustomAuthToken.Payload payload =
      new FirebaseCustomAuthToken.Payload()
          .setUid(uid)
          .setIssuer(signer.getAccount())
          .setSubject(signer.getAccount())
          .setAudience(FirebaseCustomAuthToken.FIREBASE_AUDIENCE)
          .setIssuedAtTimeSeconds(issuedAt)
          .setExpirationTimeSeconds(issuedAt + FirebaseCustomAuthToken.TOKEN_DURATION_SECONDS);

  if (developerClaims != null) {
    Collection<String> reservedNames = payload.getClassInfo().getNames();
    for (String key : developerClaims.keySet()) {
      if (reservedNames.contains(key)) {
        throw new IllegalArgumentException(
            String.format("developerClaims must not contain a reserved key: %s", key));
      }
    }
    GenericJson jsonObject = new GenericJson();
    jsonObject.putAll(developerClaims);
    payload.setDeveloperClaims(jsonObject);
  }
  return signPayload(header, payload);
}
 
Example #16
Source File: FirebaseTokenVerifierImplTest.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private String createTokenWithIncorrectAlgorithm() {
  JsonWebSignature.Header header = tokenFactory.createHeader();
  header.setAlgorithm("HSA");
  return tokenFactory.createToken(header);
}
 
Example #17
Source File: FirebaseTokenVerifierImplTest.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private String createTokenWithoutKeyId() {
  JsonWebSignature.Header header = tokenFactory.createHeader();
  header.setKeyId(null);
  return tokenFactory.createToken(header);
}
 
Example #18
Source File: TestTokenFactory.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
public String createToken(JsonWebSignature.Payload payload) {
  return createToken(createHeader(), payload);
}
 
Example #19
Source File: TestTokenFactory.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
public String createToken(JsonWebSignature.Header header) {
  return createToken(header, createTokenPayload());
}
 
Example #20
Source File: MockTokenServerTransport.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
private MockLowLevelHttpRequest buildTokenRequest(String url) {
  return new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      String content = this.getContentAsString();
      Map<String, String> query = TestUtils.parseQuery(content);
      String accessToken = null;

      String foundId = query.get("client_id");
      if (foundId != null) {
        if (!clients.containsKey(foundId)) {
          throw new IOException("Client ID not found.");
        }
        String foundSecret = query.get("client_secret");
        String expectedSecret = clients.get(foundId);
        if (foundSecret == null || !foundSecret.equals(expectedSecret)) {
          throw new IOException("Client secret not found.");
        }
        String foundRefresh = query.get("refresh_token");
        if (!refreshTokens.containsKey(foundRefresh)) {
          throw new IOException("Refresh Token not found.");
        }
        accessToken = refreshTokens.get(foundRefresh);
      } else if (query.containsKey("grant_type")) {
        String grantType = query.get("grant_type");
        if (!EXPECTED_GRANT_TYPE.equals(grantType)) {
          throw new IOException("Unexpected Grant Type.");
        }
        String assertion = query.get("assertion");
        JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion);
        String foundEmail = signature.getPayload().getIssuer();
        if (!serviceAccounts.containsKey(foundEmail)) {
          throw new IOException("Service Account Email not found as issuer.");
        }
        accessToken = serviceAccounts.get(foundEmail);
        String foundScopes = (String) signature.getPayload().get("scope");
        if (foundScopes == null || foundScopes.length() == 0) {
          throw new IOException("Scopes not found.");
        }
      } else {
        throw new IOException("Unknown token type.");
      }

      // Create the JSon response
      GenericJson refreshContents = new GenericJson();
      refreshContents.setFactory(JSON_FACTORY);
      refreshContents.put("access_token", accessToken);
      refreshContents.put("expires_in", 3600);
      refreshContents.put("token_type", "Bearer");
      String refreshText  = refreshContents.toPrettyString();

      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse()
          .setContentType(Json.MEDIA_TYPE)
          .setContent(refreshText);
      return response;
    }
  };
}
 
Example #21
Source File: IdToken.java    From google-oauth-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Parses the given ID token string and returns the parsed ID token.
 *
 * @param jsonFactory JSON factory
 * @param idTokenString ID token string
 * @return parsed ID token
 */
public static IdToken parse(JsonFactory jsonFactory, String idTokenString) throws IOException {
  JsonWebSignature jws =
      JsonWebSignature.parser(jsonFactory).setPayloadClass(Payload.class).parse(idTokenString);
  return new IdToken(jws.getHeader(), (Payload) jws.getPayload(), jws.getSignatureBytes(),
      jws.getSignedContentBytes());
}