Java Code Examples for org.jose4j.jwt.consumer.JwtConsumerBuilder#build()

The following examples show how to use org.jose4j.jwt.consumer.JwtConsumerBuilder#build() . 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: Jose4jVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateToken(String token, RSAPublicKey publicKey, String issuer, int expGracePeriodSecs) throws Exception {
    JwtConsumerBuilder builder = new JwtConsumerBuilder()
        .setRequireExpirationTime()
        .setRequireSubject()
        .setSkipDefaultAudienceValidation()
        .setExpectedIssuer(issuer)
        .setJwsAlgorithmConstraints(
            new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST,
                                     AlgorithmIdentifiers.RSA_USING_SHA256));

    builder.setVerificationKey(publicKey);

    if (expGracePeriodSecs > 0) {
        builder.setAllowedClockSkewInSeconds(expGracePeriodSecs);
    }
    else {
        builder.setEvaluationTime(NumericDate.fromSeconds(0));
    }

    JwtConsumer jwtConsumer = builder.build();
    JwtContext jwtContext = jwtConsumer.process(token);
    String type = jwtContext.getJoseObjects().get(0).getHeader("typ");
    //  Validate the JWT and process it to the Claims
    jwtConsumer.processContext(jwtContext);
}
 
Example 2
Source File: JWTAuthPlugin.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void initConsumer() {
  JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder()
      .setAllowedClockSkewInSeconds(30); // allow some leeway in validating time based claims to account for clock skew
  String[] issuers = issuerConfigs.stream().map(JWTIssuerConfig::getIss).filter(Objects::nonNull).toArray(String[]::new);
  if (issuers.length > 0) {
    jwtConsumerBuilder.setExpectedIssuers(requireIssuer, issuers); // whom the JWT needs to have been issued by
  }
  String[] audiences = issuerConfigs.stream().map(JWTIssuerConfig::getAud).filter(Objects::nonNull).toArray(String[]::new);
  if (audiences.length > 0) {
    jwtConsumerBuilder.setExpectedAudience(audiences); // to whom the JWT is intended for
  } else {
    jwtConsumerBuilder.setSkipDefaultAudienceValidation();
  }
  jwtConsumerBuilder.setRequireSubject();
  if (requireExpirationTime)
    jwtConsumerBuilder.setRequireExpirationTime();
  if (algWhitelist != null)
    jwtConsumerBuilder.setJwsAlgorithmConstraints( // only allow the expected signature algorithm(s) in the given context
        new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, algWhitelist.toArray(new String[0])));
  jwtConsumerBuilder.setVerificationKeyResolver(verificationKeyResolver);
  jwtConsumer = jwtConsumerBuilder.build(); // create the JwtConsumer instance
}
 
Example 3
Source File: Jose4jJWKSTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Override
protected void validateToken(String token, URL jwksURL, String issuer, int expGracePeriodSecs) throws Exception {
    JwtConsumerBuilder builder = new JwtConsumerBuilder()
        .setRequireExpirationTime()
        .setRequireSubject()
        .setSkipDefaultAudienceValidation()
        .setExpectedIssuer(issuer)
        .setJwsAlgorithmConstraints(
            new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST,
                                     AlgorithmIdentifiers.RSA_USING_SHA256));

    HttpsJwks keySource = new HttpsJwks(jwksURL.toExternalForm());
    List<JsonWebKey> keys = keySource.getJsonWebKeys();
    JsonWebKey key = keys.get(0);
    if(key instanceof PublicJsonWebKey) {
        PublicJsonWebKey publicJsonWebKey = (PublicJsonWebKey) key;
        PublicKey pk = publicJsonWebKey.getPublicKey();
        byte[] encoded = pk.getEncoded();
        String pem = Base64.getEncoder().encodeToString(encoded);
        System.out.printf("pk.pem: %s\n", pem);
    }
    builder.setVerificationKeyResolver(new HttpsJwksVerificationKeyResolver(keySource));

    if (expGracePeriodSecs > 0) {
        builder.setAllowedClockSkewInSeconds(expGracePeriodSecs);
    }
    else {
        builder.setEvaluationTime(NumericDate.fromSeconds(0));
    }

    JwtConsumer jwtConsumer = builder.build();
    JwtContext jwtContext = jwtConsumer.process(token);
    String type = jwtContext.getJoseObjects().get(0).getHeader("typ");
    //  Validate the JWT and process it to the Claims
    jwtConsumer.processContext(jwtContext);

}
 
Example 4
Source File: PublicKeyAsJWKSTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Test
public void validateJWKS() throws Exception {
    System.setProperty(Names.VERIFIER_PUBLIC_KEY, "");
    System.setProperty(Names.VERIFIER_PUBLIC_KEY_LOCATION, "file://" +
                                                           Paths.get("").toAbsolutePath().toString() +
                                                           "/src/test/resources/signer-keyset4k.jwk");
    System.setProperty(Names.ISSUER, TCKConstants.TEST_ISSUER);

    final PrivateKey privateKey = TokenUtils.readPrivateKey("/privateKey4k.pem");
    final String kid = "publicKey4k";
    final String token = TokenUtils.generateTokenString(privateKey, kid, "/Token1.json", null, new HashMap<>());
    System.out.println("token = " + token);

    final JWTAuthConfigurationProperties JWTAuthConfigurationProperties = new JWTAuthConfigurationProperties();
    JWTAuthConfigurationProperties.init(null);

    final JWTAuthConfiguration jwtAuthConfiguration =
            JWTAuthConfigurationProperties.getJWTAuthConfiguration().orElseThrow(IllegalArgumentException::new);

    final JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder()
            .setRequireExpirationTime()
            .setRequireSubject()
            .setSkipDefaultAudienceValidation()
            .setExpectedIssuer(jwtAuthConfiguration.getIssuer())
            .setJwsAlgorithmConstraints(new AlgorithmConstraints(WHITELIST, RSA_USING_SHA256))
            .setSkipDefaultAudienceValidation()
            .setVerificationKey(jwtAuthConfiguration.getPublicKey());

    if (jwtAuthConfiguration.getExpGracePeriodSecs() > 0) {
        jwtConsumerBuilder.setAllowedClockSkewInSeconds(jwtAuthConfiguration.getExpGracePeriodSecs());
    } else {
        jwtConsumerBuilder.setEvaluationTime(NumericDate.fromSeconds(0));
    }

    if (jwtAuthConfiguration.isSingleKey()) {
        jwtConsumerBuilder.setVerificationKey(jwtAuthConfiguration.getPublicKey());
    } else {
        jwtConsumerBuilder.setVerificationKeyResolver(new JwksVerificationKeyResolver(jwtAuthConfiguration.getPublicKeys()));
    }

    final JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
    final JwtContext jwtContext = jwtConsumer.process(token);
    Assert.assertEquals(jwtContext.getJwtClaims().getStringClaimValue("upn"), "[email protected]");
}