Java Code Examples for com.google.api.client.json.webtoken.JsonWebSignature#Header

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: 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: 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 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: 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 5
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 6
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 7
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 8
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 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;
  }
}
 
Example 11
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 12
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 13
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);
}