Search in sources :

Example 21 with JsonWebKeySet

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

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

Example 23 with JsonWebKeySet

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

the class OidcJwksEndpointController method handleRequestInternal.

/**
 * Handle request for jwk set.
 *
 * @param request  the request
 * @param response the response
 * @param model    the model
 * @return the jwk set
 */
@GetMapping(value = '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.JWKS_URL, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response, final Model model) {
    try {
        final String jsonJwks = IOUtils.toString(this.jwksFile.getInputStream(), StandardCharsets.UTF_8);
        final JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jsonJwks);
        this.servicesManager.getAllServices().stream().filter(s -> s instanceof OidcRegisteredService && StringUtils.isNotBlank(((OidcRegisteredService) s).getJwks())).forEach(Unchecked.consumer(s -> {
            final OidcRegisteredService service = (OidcRegisteredService) s;
            final Resource resource = this.resourceLoader.getResource(service.getJwks());
            final JsonWebKeySet set = new JsonWebKeySet(IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8));
            set.getJsonWebKeys().forEach(jsonWebKeySet::addJsonWebKey);
        }));
        final String body = jsonWebKeySet.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        return new ResponseEntity<>(body, HttpStatus.OK);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) BaseOAuth20Controller(org.apereo.cas.support.oauth.web.endpoints.BaseOAuth20Controller) OAuth20Validator(org.apereo.cas.support.oauth.validator.OAuth20Validator) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) Model(org.springframework.ui.Model) HttpServletRequest(javax.servlet.http.HttpServletRequest) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) CookieRetrievingCookieGenerator(org.apereo.cas.web.support.CookieRetrievingCookieGenerator) GetMapping(org.springframework.web.bind.annotation.GetMapping) ServiceFactory(org.apereo.cas.authentication.principal.ServiceFactory) ServicesManager(org.apereo.cas.services.ServicesManager) Resource(org.springframework.core.io.Resource) Unchecked(org.jooq.lambda.Unchecked) ResourceLoader(org.springframework.core.io.ResourceLoader) OAuth20ProfileScopeToAttributesFilter(org.apereo.cas.support.oauth.profile.OAuth20ProfileScopeToAttributesFilter) NonNull(lombok.NonNull) OidcConstants(org.apereo.cas.oidc.OidcConstants) JsonWebKey(org.jose4j.jwk.JsonWebKey) MediaType(org.springframework.http.MediaType) HttpServletResponse(javax.servlet.http.HttpServletResponse) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) StandardCharsets(java.nio.charset.StandardCharsets) IOUtils(org.apache.commons.io.IOUtils) AccessTokenFactory(org.apereo.cas.ticket.accesstoken.AccessTokenFactory) HttpStatus(org.springframework.http.HttpStatus) Slf4j(lombok.extern.slf4j.Slf4j) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) ResponseEntity(org.springframework.http.ResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) Resource(org.springframework.core.io.Resource) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 24 with JsonWebKeySet

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

the class OidcRegisteredServiceJwtAccessTokenCipherExecutorNoCacheTests method verifyCipherOperation.

@Test
public void verifyCipherOperation() {
    val id = UUID.randomUUID().toString();
    val defaultCache = mock(LoadingCache.class);
    when(defaultCache.get(any())).thenReturn(Optional.empty());
    val serviceCache = mock(LoadingCache.class);
    when(serviceCache.get(any())).thenReturn(Optional.empty());
    val cipher = new OidcRegisteredServiceJwtAccessTokenCipherExecutor(defaultCache, serviceCache, OidcIssuerService.immutable(id));
    val service = getOidcRegisteredService("whatever");
    val exec = cipher.createCipherExecutorInstance(null, null, service, BaseStringCipherExecutor.CipherOperationsStrategyType.ENCRYPT_AND_SIGN);
    assertEquals("value", exec.decode("value", new Object[] { service }));
    when(serviceCache.get(any())).thenReturn(Optional.of(new JsonWebKeySet(mock(PublicJsonWebKey.class))));
    assertEquals("value", exec.decode("value", new Object[] { service }));
}
Also used : lombok.val(lombok.val) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) PublicJsonWebKey(org.jose4j.jwk.PublicJsonWebKey) Test(org.junit.jupiter.api.Test)

Example 25 with JsonWebKeySet

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

the class OidcGroovyJsonWebKeystoreGeneratorServiceTests method verifyOperation.

@Test
public void verifyOperation() throws Exception {
    val resource = oidcJsonWebKeystoreGeneratorService.generate();
    assertTrue(resource.exists());
    assertTrue(oidcJsonWebKeystoreGeneratorService.find().isPresent());
    assertDoesNotThrow(new Executable() {

        @Override
        public void execute() throws Throwable {
            val results = new String(IOUtils.toByteArray(resource.getInputStream()), StandardCharsets.UTF_8);
            new JsonWebKeySet(results);
        }
    });
}
Also used : lombok.val(lombok.val) Executable(org.junit.jupiter.api.function.Executable) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) Test(org.junit.jupiter.api.Test)

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