use of org.keycloak.jose.jwk.JSONWebKeySet in project keycloak by keycloak.
the class ClientAttributeCertificateResource method getCertFromRequest.
private CertificateRepresentation getCertFromRequest(MultipartFormDataInput input) throws IOException {
auth.clients().requireManage(client);
CertificateRepresentation info = new CertificateRepresentation();
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> keystoreFormatPart = uploadForm.get("keystoreFormat");
if (keystoreFormatPart == null)
throw new BadRequestException();
String keystoreFormat = keystoreFormatPart.get(0).getBodyAsString();
List<InputPart> inputParts = uploadForm.get("file");
if (keystoreFormat.equals(CERTIFICATE_PEM)) {
String pem = StreamUtil.readString(inputParts.get(0).getBody(InputStream.class, null));
pem = PemUtils.removeBeginEnd(pem);
// Validate format
KeycloakModelUtils.getCertificate(pem);
info.setCertificate(pem);
return info;
} else if (keystoreFormat.equals(PUBLIC_KEY_PEM)) {
String pem = StreamUtil.readString(inputParts.get(0).getBody(InputStream.class, null));
// Validate format
KeycloakModelUtils.getPublicKey(pem);
info.setPublicKey(pem);
return info;
} else if (keystoreFormat.equals(JSON_WEB_KEY_SET)) {
InputStream stream = inputParts.get(0).getBody(InputStream.class, null);
JSONWebKeySet keySet = JsonSerialization.readValue(stream, JSONWebKeySet.class);
JWK publicKeyJwk = JWKSUtils.getKeyForUse(keySet, JWK.Use.SIG);
if (publicKeyJwk == null) {
throw new IllegalStateException("Certificate not found for use sig");
} else {
PublicKey publicKey = JWKParser.create(publicKeyJwk).toPublicKey();
String publicKeyPem = KeycloakModelUtils.getPemFromKey(publicKey);
info.setPublicKey(publicKeyPem);
info.setKid(publicKeyJwk.getKeyId());
return info;
}
}
String keyAlias = uploadForm.get("keyAlias").get(0).getBodyAsString();
List<InputPart> keyPasswordPart = uploadForm.get("keyPassword");
char[] keyPassword = keyPasswordPart != null ? keyPasswordPart.get(0).getBodyAsString().toCharArray() : null;
List<InputPart> storePasswordPart = uploadForm.get("storePassword");
char[] storePassword = storePasswordPart != null ? storePasswordPart.get(0).getBodyAsString().toCharArray() : null;
PrivateKey privateKey = null;
X509Certificate certificate = null;
try {
KeyStore keyStore = null;
if (keystoreFormat.equals("JKS"))
keyStore = KeyStore.getInstance("JKS");
else
keyStore = KeyStore.getInstance(keystoreFormat, "BC");
keyStore.load(inputParts.get(0).getBody(InputStream.class, null), storePassword);
try {
privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword);
} catch (Exception e) {
// ignore
}
certificate = (X509Certificate) keyStore.getCertificate(keyAlias);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (privateKey != null) {
String privateKeyPem = KeycloakModelUtils.getPemFromKey(privateKey);
info.setPrivateKey(privateKeyPem);
}
if (certificate != null) {
String certPem = KeycloakModelUtils.getPemFromCertificate(certificate);
info.setCertificate(certPem);
}
return info;
}
use of org.keycloak.jose.jwk.JSONWebKeySet in project keycloak by keycloak.
the class TLSTest method testSSLAlwaysRequired.
@Test
public void testSSLAlwaysRequired() throws Exception {
// Switch realm SSLRequired to Always
RealmRepresentation realmRep = testRealm().toRepresentation();
String origSslRequired = realmRep.getSslRequired();
realmRep.setSslRequired(SslRequired.ALL.toString());
testRealm().update(realmRep);
// Try access "WellKnown" endpoint unsecured. It should fail
oauth.baseUrl(AUTH_SERVER_ROOT_WITHOUT_TLS);
OIDCConfigurationRepresentation config = oauth.doWellKnownRequest("test");
Assert.assertNull(config.getAuthorizationEndpoint());
Assert.assertEquals("HTTPS required", config.getOtherClaims().get("error_description"));
// Try access "JWKS URL" unsecured. It should fail
try {
JSONWebKeySet keySet = oauth.doCertsRequest("test");
Assert.fail("This should not be successful");
} catch (Exception e) {
// Expected
}
// Revert SSLRequired
realmRep.setSslRequired(origSslRequired);
testRealm().update(realmRep);
}
use of org.keycloak.jose.jwk.JSONWebKeySet in project keycloak by keycloak.
the class OIDCAdvancedRequestParamsTest method createEncryptedRequestObject.
private String createEncryptedRequestObject(String encAlg) throws IOException, JWEException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
OIDCConfigurationRepresentation representation = SimpleHttp.doGet(getAuthServerRoot().toString() + "realms/" + oauth.getRealm() + "/.well-known/openid-configuration", httpClient).asJson(OIDCConfigurationRepresentation.class);
String jwksUri = representation.getJwksUri();
JSONWebKeySet jsonWebKeySet = SimpleHttp.doGet(jwksUri, httpClient).asJson(JSONWebKeySet.class);
Map<String, PublicKey> keysForUse = JWKSUtils.getKeysForUse(jsonWebKeySet, JWK.Use.ENCRYPTION);
String keyId = null;
if (keyId == null) {
KeysMetadataRepresentation.KeyMetadataRepresentation encKey = KeyUtils.getActiveEncKey(testRealm().keys().getKeyMetadata(), org.keycloak.crypto.Algorithm.PS256);
keyId = encKey.getKid();
}
PublicKey decryptionKEK = keysForUse.get(keyId);
JWE jwe = new JWE().header(new JWEHeader(encAlg, JWEConstants.A256GCM, null)).content(createAndSignRequestObject().getBytes());
jwe.getKeyStorage().setEncryptionKey(decryptionKEK);
return jwe.encodeJwe();
}
}
use of org.keycloak.jose.jwk.JSONWebKeySet in project keycloak by keycloak.
the class TestingOIDCEndpointsApplicationResource method getJwks.
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/get-jwks")
@NoCache
public JSONWebKeySet getJwks() {
JSONWebKeySet keySet = new JSONWebKeySet();
KeyPair keyPair = clientData.getKeyPair();
String keyAlgorithm = clientData.getKeyAlgorithm();
String keyType = clientData.getKeyType();
KeyUse keyUse = clientData.getKeyUse();
if (keyPair == null) {
keySet.setKeys(new JWK[] {});
} else if (KeyType.RSA.equals(keyType)) {
keySet.setKeys(new JWK[] { JWKBuilder.create().algorithm(keyAlgorithm).rsa(keyPair.getPublic(), keyUse) });
} else if (KeyType.EC.equals(keyType)) {
keySet.setKeys(new JWK[] { JWKBuilder.create().algorithm(keyAlgorithm).ec(keyPair.getPublic()) });
} else {
keySet.setKeys(new JWK[] {});
}
return keySet;
}
use of org.keycloak.jose.jwk.JSONWebKeySet in project keycloak by keycloak.
the class OIDCJwksClientRegistrationTest method createClientWithJWKS_nullKid.
// The "kid" is null in the signed JWT. This is backwards compatibility test as in versions prior to 2.3.0, the "kid" wasn't set by JWTClientCredentialsProvider
@Test
public void createClientWithJWKS_nullKid() throws Exception {
OIDCClientRepresentation clientRep = createRep();
clientRep.setGrantTypes(Collections.singletonList(OAuth2Constants.CLIENT_CREDENTIALS));
clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.PRIVATE_KEY_JWT);
// Generate keys for client
TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
Map<String, String> generatedKeys = oidcClientEndpointsResource.generateKeys("RS256");
JSONWebKeySet keySet = oidcClientEndpointsResource.getJwks();
clientRep.setJwks(keySet);
OIDCClientRepresentation response = reg.oidc().create(clientRep);
// Tries to authenticate client with privateKey JWT
assertAuthenticateClientSuccess(generatedKeys, response, null);
}
Aggregations