Search in sources :

Example 6 with RsaJsonWebKey

use of org.jose4j.jwk.RsaJsonWebKey in project blueocean-plugin by jenkinsci.

the class JwtImplTest method getToken.

@Test
public void getToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    User user = j.jenkins.getUser("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
    JenkinsRule.WebClient webClient = j.createWebClient();
    webClient.login("alice");
    Page page = webClient.goTo("jwt-auth/token/", null);
    String token = page.getWebResponse().getResponseHeaderValue("X-BLUEOCEAN-JWT");
    Assert.assertNotNull(token);
    JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);
    Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);
    JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;
    System.out.println(token);
    System.out.println(jsw.toString());
    String kid = jsw.getHeader("kid");
    Assert.assertNotNull(kid);
    page = webClient.goTo("jwt-auth/jwks/" + kid + "/", "application/json");
    //        for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
    //            System.out.println(valuePair);
    //        }
    JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
    System.out.println(jsonObject.toString());
    RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject, null);
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
    30).setRequireSubject().setVerificationKey(// verify the sign with the public key
    rsaJsonWebKey.getKey()).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) Page(com.gargoylesoftware.htmlunit.Page) JenkinsRule(org.jvnet.hudson.test.JenkinsRule) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JSONObject(net.sf.json.JSONObject) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JSONObject(net.sf.json.JSONObject) RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) Map(java.util.Map) JsonWebStructure(org.jose4j.jwx.JsonWebStructure) Test(org.junit.Test)

Example 7 with RsaJsonWebKey

use of org.jose4j.jwk.RsaJsonWebKey in project cas by apereo.

the class OidcDefaultJsonWebKeystoreCacheLoader method load.

@Override
public Optional<RsaJsonWebKey> load(final String issuer) throws Exception {
    final Optional<JsonWebKeySet> jwks = buildJsonWebKeySet();
    if (!jwks.isPresent() || jwks.get().getJsonWebKeys().isEmpty()) {
        return Optional.empty();
    }
    final RsaJsonWebKey key = getJsonSigningWebKeyFromJwks(jwks.get());
    if (key == null) {
        return Optional.empty();
    }
    return Optional.of(key);
}
Also used : RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet)

Example 8 with RsaJsonWebKey

use of org.jose4j.jwk.RsaJsonWebKey in project cas by apereo.

the class OidcDefaultJsonWebKeystoreCacheLoader method buildJsonWebKeySet.

/**
 * Build json web key set.
 *
 * @return the json web key set
 */
private Optional<JsonWebKeySet> buildJsonWebKeySet() {
    try {
        LOGGER.debug("Loading default JSON web key from [{}]", this.jwksFile);
        if (this.jwksFile != null) {
            LOGGER.debug("Retrieving default JSON web key from [{}]", this.jwksFile);
            final JsonWebKeySet jsonWebKeySet = buildJsonWebKeySet(this.jwksFile);
            if (jsonWebKeySet == null || jsonWebKeySet.getJsonWebKeys().isEmpty()) {
                LOGGER.warn("No JSON web keys could be found");
                return Optional.empty();
            }
            final long badKeysCount = jsonWebKeySet.getJsonWebKeys().stream().filter(k -> StringUtils.isBlank(k.getAlgorithm()) && StringUtils.isBlank(k.getKeyId()) && StringUtils.isBlank(k.getKeyType())).count();
            if (badKeysCount == jsonWebKeySet.getJsonWebKeys().size()) {
                LOGGER.warn("No valid JSON web keys could be found");
                return Optional.empty();
            }
            final RsaJsonWebKey webKey = getJsonSigningWebKeyFromJwks(jsonWebKeySet);
            if (webKey.getPrivateKey() == null) {
                LOGGER.warn("JSON web key retrieved [{}] has no associated private key", webKey.getKeyId());
                return Optional.empty();
            }
            return Optional.of(jsonWebKeySet);
        }
    } catch (final Exception e) {
        LOGGER.debug(e.getMessage(), e);
    }
    return Optional.empty();
}
Also used : IOUtils(org.apache.commons.io.IOUtils) Slf4j(lombok.extern.slf4j.Slf4j) CacheLoader(com.github.benmanes.caffeine.cache.CacheLoader) RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) Optional(java.util.Optional) AllArgsConstructor(lombok.AllArgsConstructor) StringUtils(org.apache.commons.lang3.StringUtils) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) StandardCharsets(java.nio.charset.StandardCharsets) Resource(org.springframework.core.io.Resource) RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet)

Example 9 with RsaJsonWebKey

use of org.jose4j.jwk.RsaJsonWebKey in project cas by apereo.

the class OidcJsonWebKeystoreGeneratorService method generate.

/**
 * Generate.
 */
@PostConstruct
@SneakyThrows
public void generate() {
    final File file = oidcProperties.getJwksFile().getFile();
    if (!file.exists()) {
        final RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
        final JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(rsaJsonWebKey);
        final String data = jsonWebKeySet.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
        FileUtils.write(file, data, StandardCharsets.UTF_8);
        LOGGER.debug("Generated JSON web keystore at [{}]", file);
    } else {
        LOGGER.debug("Located JSON web keystore at [{}]", file);
    }
}
Also used : RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) File(java.io.File) SneakyThrows(lombok.SneakyThrows) PostConstruct(javax.annotation.PostConstruct)

Example 10 with RsaJsonWebKey

use of org.jose4j.jwk.RsaJsonWebKey in project cas by apereo.

the class OidcServiceJsonWebKeystoreCacheLoader method buildJsonWebKeySet.

private Optional<JsonWebKeySet> buildJsonWebKeySet(final OidcRegisteredService service) {
    try {
        LOGGER.debug("Loading JSON web key from [{}]", service.getJwks());
        final Resource resource = this.resourceLoader.getResource(service.getJwks());
        final JsonWebKeySet jsonWebKeySet = buildJsonWebKeySet(resource);
        if (jsonWebKeySet == null || jsonWebKeySet.getJsonWebKeys().isEmpty()) {
            LOGGER.warn("No JSON web keys could be found for [{}]", service);
            return Optional.empty();
        }
        final long badKeysCount = jsonWebKeySet.getJsonWebKeys().stream().filter(k -> StringUtils.isBlank(k.getAlgorithm()) && StringUtils.isBlank(k.getKeyId()) && StringUtils.isBlank(k.getKeyType())).count();
        if (badKeysCount == jsonWebKeySet.getJsonWebKeys().size()) {
            LOGGER.warn("No valid JSON web keys could be found for [{}]", service);
            return Optional.empty();
        }
        final RsaJsonWebKey webKey = getJsonSigningWebKeyFromJwks(jsonWebKeySet);
        if (webKey.getPublicKey() == null) {
            LOGGER.warn("JSON web key retrieved [{}] has no associated public key", webKey.getKeyId());
            return Optional.empty();
        }
        return Optional.of(jsonWebKeySet);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return Optional.empty();
}
Also used : IOUtils(org.apache.commons.io.IOUtils) Slf4j(lombok.extern.slf4j.Slf4j) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) ResourceLoader(org.springframework.core.io.ResourceLoader) CacheLoader(com.github.benmanes.caffeine.cache.CacheLoader) RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) Autowired(org.springframework.beans.factory.annotation.Autowired) Optional(java.util.Optional) StringUtils(org.apache.commons.lang3.StringUtils) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) StandardCharsets(java.nio.charset.StandardCharsets) Resource(org.springframework.core.io.Resource) Resource(org.springframework.core.io.Resource) RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet)

Aggregations

RsaJsonWebKey (org.jose4j.jwk.RsaJsonWebKey)13 JsonWebKeySet (org.jose4j.jwk.JsonWebKeySet)7 Page (com.gargoylesoftware.htmlunit.Page)4 Map (java.util.Map)4 JSONObject (net.sf.json.JSONObject)4 JsonWebSignature (org.jose4j.jws.JsonWebSignature)4 JwtClaims (org.jose4j.jwt.JwtClaims)4 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)4 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)4 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)4 Test (org.junit.Test)4 JenkinsRule (org.jvnet.hudson.test.JenkinsRule)4 CacheLoader (com.github.benmanes.caffeine.cache.CacheLoader)2 User (hudson.model.User)2 Mailer (hudson.tasks.Mailer)2 StandardCharsets (java.nio.charset.StandardCharsets)2 Optional (java.util.Optional)2 Slf4j (lombok.extern.slf4j.Slf4j)2 IOUtils (org.apache.commons.io.IOUtils)2 StringUtils (org.apache.commons.lang3.StringUtils)2