1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.syncope.wa.starter.oidc;
20
21 import java.nio.charset.StandardCharsets;
22 import java.util.Optional;
23 import javax.ws.rs.core.Response;
24 import org.apache.syncope.common.lib.SyncopeClientException;
25 import org.apache.syncope.common.lib.to.OIDCJWKSTO;
26 import org.apache.syncope.common.lib.types.ClientExceptionType;
27 import org.apache.syncope.common.rest.api.service.OIDCJWKSService;
28 import org.apache.syncope.wa.bootstrap.WARestClient;
29 import org.apereo.cas.oidc.jwks.generator.OidcJsonWebKeystoreGeneratorService;
30 import org.jose4j.jwk.JsonWebKey;
31 import org.jose4j.jwk.JsonWebKeySet;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.core.io.ByteArrayResource;
35 import org.springframework.core.io.Resource;
36
37 public class WAOIDCJWKSGeneratorService implements OidcJsonWebKeystoreGeneratorService {
38
39 protected static final Logger LOG = LoggerFactory.getLogger(WAOIDCJWKSGeneratorService.class);
40
41 protected final WARestClient waRestClient;
42
43 protected final String jwksKeyId;
44
45 protected final String jwksType;
46
47 protected final int jwksKeySize;
48
49 public WAOIDCJWKSGeneratorService(
50 final WARestClient waRestClient,
51 final String jwksKeyId,
52 final String jwksType,
53 final int jwksKeySize) {
54
55 this.waRestClient = waRestClient;
56 this.jwksKeyId = jwksKeyId;
57 this.jwksType = jwksType;
58 this.jwksKeySize = jwksKeySize;
59 }
60
61 @Override
62 public JsonWebKeySet store(final JsonWebKeySet jsonWebKeySet) throws Exception {
63 OIDCJWKSService service = waRestClient.getService(OIDCJWKSService.class);
64 OIDCJWKSTO to = new OIDCJWKSTO();
65 to.setJson(jsonWebKeySet.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE));
66 service.set(to);
67 return jsonWebKeySet;
68 }
69
70 @Override
71 public Optional<Resource> find() {
72 return Optional.of(generate());
73 }
74
75 @Override
76 public Resource generate() {
77 OIDCJWKSService service = waRestClient.getService(OIDCJWKSService.class);
78 OIDCJWKSTO jwksTO = null;
79 try {
80 jwksTO = service.get();
81 } catch (SyncopeClientException e) {
82 if (e.getType() == ClientExceptionType.NotFound) {
83 try {
84 Response response = service.generate(jwksKeyId, jwksType, jwksKeySize);
85 jwksTO = response.readEntity(OIDCJWKSTO.class);
86 } catch (Exception ge) {
87 LOG.error("While generating new OIDC JWKS", ge);
88 }
89 } else {
90 LOG.error("While reading OIDC JWKS", e);
91 }
92 }
93 if (jwksTO == null) {
94 throw new IllegalStateException("Unable to determine OIDC JWKS resource");
95 }
96 return new ByteArrayResource(jwksTO.getJson().getBytes(StandardCharsets.UTF_8), "OIDC JWKS");
97 }
98 }