Search in sources :

Example 1 with JwksVerificationKeyResolver

use of org.jose4j.keys.resolvers.JwksVerificationKeyResolver in project kafka by apache.

the class JwksFileVerificationKeyResolver method init.

@Override
public void init() throws IOException {
    log.debug("Starting creation of new VerificationKeyResolver from {}", jwksFile);
    String json = Utils.readFileAsString(jwksFile.toFile().getPath());
    JsonWebKeySet jwks;
    try {
        jwks = new JsonWebKeySet(json);
    } catch (JoseException e) {
        throw new IOException(e);
    }
    delegate = new JwksVerificationKeyResolver(jwks.getJsonWebKeys());
}
Also used : JoseException(org.jose4j.lang.JoseException) IOException(java.io.IOException) JwksVerificationKeyResolver(org.jose4j.keys.resolvers.JwksVerificationKeyResolver) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet)

Example 2 with JwksVerificationKeyResolver

use of org.jose4j.keys.resolvers.JwksVerificationKeyResolver in project tomee by apache.

the class JsonWebTokenValidator method validate.

public JsonWebToken validate(final String token) throws ParseException {
    final JWTAuthConfiguration authConfiguration = verificationKey != null ? JWTAuthConfiguration.authConfiguration(verificationKey, issuer, allowNoExpiryClaim) : JWTAuthConfiguration.authConfiguration(verificationKeys, issuer, allowNoExpiryClaim);
    JWTCallerPrincipal principal;
    try {
        final JwtConsumerBuilder builder = new JwtConsumerBuilder().setRelaxVerificationKeyValidation().setRequireSubject().setSkipDefaultAudienceValidation().setJwsAlgorithmConstraints(new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256, AlgorithmIdentifiers.RSA_USING_SHA384, AlgorithmIdentifiers.RSA_USING_SHA512));
        if (authConfiguration.getIssuer() != null) {
            builder.setExpectedIssuer(authConfiguration.getIssuer());
        }
        if (authConfiguration.getExpGracePeriodSecs() > 0) {
            builder.setAllowedClockSkewInSeconds(authConfiguration.getExpGracePeriodSecs());
        } else {
            builder.setEvaluationTime(NumericDate.fromSeconds(0));
        }
        if (authConfiguration.isSingleKey()) {
            builder.setVerificationKey(authConfiguration.getPublicKey());
        } else {
            builder.setVerificationKeyResolver(new JwksVerificationKeyResolver(authConfiguration.getPublicKeys()));
        }
        final JwtConsumer jwtConsumer = builder.build();
        final JwtContext jwtContext = jwtConsumer.process(token);
        final String type = jwtContext.getJoseObjects().get(0).getHeader("typ");
        // Validate the JWT and process it to the Claims
        jwtConsumer.processContext(jwtContext);
        JwtClaims claimsSet = jwtContext.getJwtClaims();
        // We have to determine the unique name to use as the principal name. It comes from upn, preferred_username, sub in that order
        String principalName = claimsSet.getClaimValue("upn", String.class);
        if (principalName == null) {
            principalName = claimsSet.getClaimValue("preferred_username", String.class);
            if (principalName == null) {
                principalName = claimsSet.getSubject();
            }
        }
        claimsSet.setClaim(Claims.raw_token.name(), token);
        principal = new JWTCallerPrincipal(token, type, claimsSet, principalName);
    } catch (final InvalidJwtException e) {
        VALIDATION.warning(e.getMessage());
        throw new ParseException("Failed to verify token", e);
    } catch (final MalformedClaimException e) {
        VALIDATION.warning(e.getMessage());
        throw new ParseException("Failed to verify token claims", e);
    }
    return principal;
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JwtClaims(org.jose4j.jwt.JwtClaims) JWTAuthConfiguration(org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JwtContext(org.jose4j.jwt.consumer.JwtContext) JwksVerificationKeyResolver(org.jose4j.keys.resolvers.JwksVerificationKeyResolver) JWTCallerPrincipal(org.apache.tomee.microprofile.jwt.principal.JWTCallerPrincipal) AlgorithmConstraints(org.jose4j.jwa.AlgorithmConstraints)

Example 3 with JwksVerificationKeyResolver

use of org.jose4j.keys.resolvers.JwksVerificationKeyResolver in project blueocean-plugin by jenkinsci.

the class JwtAuthenticationServiceImplTest method getJwks.

@Test
public void getJwks() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    JenkinsRule.WebClient webClient = j.createWebClient();
    User user = User.get("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
    webClient.login("alice");
    // this call triggers the creation of a RSA key in RSAConfidentialKey::getPrivateKey
    String token = getToken(webClient);
    String jwksPayload = webClient.goTo("jwt-auth/jwk-set", "application/json").getWebResponse().getContentAsString();
    System.out.println(jwksPayload);
    JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jwksPayload);
    JwksVerificationKeyResolver jwksResolver = new JwksVerificationKeyResolver(jsonWebKeySet.getJsonWebKeys());
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
    30).setRequireSubject().setVerificationKeyResolver(// verify the sign with the public key
    jwksResolver).build();
    JwtClaims claims = jwtConsumer.processToClaims(token);
    Assert.assertEquals("alice", claims.getSubject());
    Map<String, Object> claimMap = claims.getClaimsMap();
    Map<String, Object> context = (Map<String, Object>) claimMap.get("context");
    Map<String, String> userContext = (Map<String, String>) context.get("user");
    Assert.assertEquals("alice", userContext.get("id"));
    Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
    Assert.assertEquals("alice@jenkins-ci.org", userContext.get("email"));
}
Also used : User(hudson.model.User) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) Mailer(hudson.tasks.Mailer) JenkinsRule(org.jvnet.hudson.test.JenkinsRule) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JSONObject(net.sf.json.JSONObject) JwksVerificationKeyResolver(org.jose4j.keys.resolvers.JwksVerificationKeyResolver) Map(java.util.Map) Test(org.junit.Test)

Example 4 with JwksVerificationKeyResolver

use of org.jose4j.keys.resolvers.JwksVerificationKeyResolver in project tomee by apache.

the class PublicKeyAsJWKSTest method validateJWKS.

@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"), "jdoe@example.com");
}
Also used : PrivateKey(java.security.PrivateKey) JWTAuthConfiguration(org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JwtContext(org.jose4j.jwt.consumer.JwtContext) JwksVerificationKeyResolver(org.jose4j.keys.resolvers.JwksVerificationKeyResolver) JWTAuthConfigurationProperties(org.apache.tomee.microprofile.jwt.config.JWTAuthConfigurationProperties) AlgorithmConstraints(org.jose4j.jwa.AlgorithmConstraints) Test(org.testng.annotations.Test)

Aggregations

JwksVerificationKeyResolver (org.jose4j.keys.resolvers.JwksVerificationKeyResolver)4 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)3 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)3 JWTAuthConfiguration (org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration)2 AlgorithmConstraints (org.jose4j.jwa.AlgorithmConstraints)2 JsonWebKeySet (org.jose4j.jwk.JsonWebKeySet)2 JwtClaims (org.jose4j.jwt.JwtClaims)2 JwtContext (org.jose4j.jwt.consumer.JwtContext)2 User (hudson.model.User)1 Mailer (hudson.tasks.Mailer)1 IOException (java.io.IOException)1 PrivateKey (java.security.PrivateKey)1 Map (java.util.Map)1 JSONObject (net.sf.json.JSONObject)1 JWTAuthConfigurationProperties (org.apache.tomee.microprofile.jwt.config.JWTAuthConfigurationProperties)1 JWTCallerPrincipal (org.apache.tomee.microprofile.jwt.principal.JWTCallerPrincipal)1 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)1 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)1 JoseException (org.jose4j.lang.JoseException)1 Test (org.junit.Test)1