Search in sources :

Example 16 with JsonWebKeySet

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

the class OidcDefaultJsonWebKeystoreRotationService method revoke.

@Override
public JsonWebKeySet revoke() throws Exception {
    return whenKeystoreResourceExists().map(Unchecked.function(resource -> {
        LOGGER.trace("Revoking previous keys found in [{}]", resource);
        val jwksJson = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
        val jsonWebKeySet = new JsonWebKeySet(jwksJson);
        jsonWebKeySet.getJsonWebKeys().removeIf(key -> {
            LOGGER.debug("Processing key [{}] to determine revocation eligibility", key.getKeyId());
            val state = JsonWebKeyLifecycleStates.getJsonWebKeyState(key);
            return state == JsonWebKeyLifecycleStates.PREVIOUS;
        });
        return generatorService.store(jsonWebKeySet);
    })).orElse(null);
}
Also used : lombok.val(lombok.val) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet)

Example 17 with JsonWebKeySet

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

the class OidcClientRegistrationUtils method getClientRegistrationResponse.

/**
 * Gets client registration response.
 *
 * @param registeredService the registered service
 * @param serverPrefix      the server prefix
 * @return the client registration response
 */
@SneakyThrows
public static OidcClientRegistrationResponse getClientRegistrationResponse(final OidcRegisteredService registeredService, final String serverPrefix) {
    val clientResponse = new OidcClientRegistrationResponse();
    clientResponse.setApplicationType(registeredService.getApplicationType());
    clientResponse.setClientId(registeredService.getClientId());
    clientResponse.setClientSecret(registeredService.getClientSecret());
    clientResponse.setSubjectType(registeredService.getSubjectType());
    clientResponse.setTokenEndpointAuthMethod(registeredService.getTokenEndpointAuthenticationMethod());
    clientResponse.setClientName(registeredService.getName());
    clientResponse.setRedirectUris(CollectionUtils.wrap(registeredService.getServiceId()));
    clientResponse.setUserInfoSignedReponseAlg(registeredService.getUserInfoSigningAlg());
    clientResponse.setUserInfoEncryptedReponseAlg(registeredService.getUserInfoEncryptedResponseAlg());
    clientResponse.setUserInfoEncryptedReponseEncoding(registeredService.getUserInfoEncryptedResponseEncoding());
    clientResponse.setContacts(registeredService.getContacts().stream().map(RegisteredServiceContact::getName).filter(StringUtils::isNotBlank).collect(Collectors.toList()));
    clientResponse.setGrantTypes(Arrays.stream(OAuth20GrantTypes.values()).map(type -> type.getType().toLowerCase()).collect(Collectors.toList()));
    clientResponse.setResponseTypes(Arrays.stream(OAuth20ResponseTypes.values()).map(type -> type.getType().toLowerCase()).collect(Collectors.toList()));
    val validator = new SimpleUrlValidatorFactoryBean(false).getObject();
    val keystore = SpringExpressionLanguageValueResolver.getInstance().resolve(registeredService.getJwks());
    if (Objects.requireNonNull(validator).isValid(keystore)) {
        clientResponse.setJwksUri(keystore);
    } else if (ResourceUtils.doesResourceExist(keystore)) {
        val res = ResourceUtils.getResourceFrom(keystore);
        val json = IOUtils.toString(res.getInputStream(), StandardCharsets.UTF_8);
        clientResponse.setJwks(new JsonWebKeySet(json).toJson());
    } else if (StringUtils.isNotBlank(keystore)) {
        val jwks = new JsonWebKeySet(keystore);
        clientResponse.setJwks(jwks.toJson());
    }
    clientResponse.setLogo(registeredService.getLogo());
    clientResponse.setPolicyUri(registeredService.getInformationUrl());
    clientResponse.setTermsOfUseUri(registeredService.getPrivacyUrl());
    clientResponse.setRedirectUris(CollectionUtils.wrapList(registeredService.getServiceId()));
    val clientConfigUri = getClientConfigurationUri(registeredService, serverPrefix);
    clientResponse.setRegistrationClientUri(clientConfigUri);
    return clientResponse;
}
Also used : lombok.val(lombok.val) SimpleUrlValidatorFactoryBean(org.apereo.cas.web.SimpleUrlValidatorFactoryBean) StringUtils(org.apache.commons.lang3.StringUtils) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) OidcClientRegistrationResponse(org.apereo.cas.oidc.dynareg.OidcClientRegistrationResponse) SneakyThrows(lombok.SneakyThrows)

Example 18 with JsonWebKeySet

use of org.jose4j.jwk.JsonWebKeySet 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 19 with JsonWebKeySet

use of org.jose4j.jwk.JsonWebKeySet 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 20 with JsonWebKeySet

use of org.jose4j.jwk.JsonWebKeySet 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)

Aggregations

JsonWebKeySet (org.jose4j.jwk.JsonWebKeySet)35 lombok.val (lombok.val)24 Test (org.junit.jupiter.api.Test)14 StringUtils (org.apache.commons.lang3.StringUtils)7 RsaJsonWebKey (org.jose4j.jwk.RsaJsonWebKey)7 Optional (java.util.Optional)6 Slf4j (lombok.extern.slf4j.Slf4j)6 JsonWebKey (org.jose4j.jwk.JsonWebKey)6 PublicJsonWebKey (org.jose4j.jwk.PublicJsonWebKey)6 Resource (org.springframework.core.io.Resource)6 StandardCharsets (java.nio.charset.StandardCharsets)4 IOUtils (org.apache.commons.io.IOUtils)4 CacheLoader (com.github.benmanes.caffeine.cache.CacheLoader)3 RequiredArgsConstructor (lombok.RequiredArgsConstructor)3 SneakyThrows (lombok.SneakyThrows)3 OidcRegisteredService (org.apereo.cas.services.OidcRegisteredService)3 ResponseEntity (org.springframework.http.ResponseEntity)3 GetMapping (org.springframework.web.bind.annotation.GetMapping)3 IOException (java.io.IOException)2 Key (java.security.Key)2