Search in sources :

Example 11 with JSONWebKeySet

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;
}
Also used : PrivateKey(java.security.PrivateKey) JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) CertificateRepresentation(org.keycloak.representations.idm.CertificateRepresentation) InputStream(java.io.InputStream) PublicKey(java.security.PublicKey) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) ErrorResponseException(org.keycloak.services.ErrorResponseException) BadRequestException(javax.ws.rs.BadRequestException) NotAcceptableException(javax.ws.rs.NotAcceptableException) IOException(java.io.IOException) NotFoundException(javax.ws.rs.NotFoundException) InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart) BadRequestException(javax.ws.rs.BadRequestException) List(java.util.List) JWK(org.keycloak.jose.jwk.JWK)

Example 12 with JSONWebKeySet

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);
}
Also used : JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) OIDCConfigurationRepresentation(org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 13 with JSONWebKeySet

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();
    }
}
Also used : KeysMetadataRepresentation(org.keycloak.representations.idm.KeysMetadataRepresentation) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) JWEHeader(org.keycloak.jose.jwe.JWEHeader) JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) PublicKey(java.security.PublicKey) JWE(org.keycloak.jose.jwe.JWE) OIDCConfigurationRepresentation(org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation)

Example 14 with JSONWebKeySet

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;
}
Also used : KeyPair(java.security.KeyPair) JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) KeyUse(org.keycloak.crypto.KeyUse) JWK(org.keycloak.jose.jwk.JWK) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 15 with JSONWebKeySet

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);
}
Also used : TestOIDCEndpointsApplicationResource(org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) Test(org.junit.Test)

Aggregations

JSONWebKeySet (org.keycloak.jose.jwk.JSONWebKeySet)18 PublicKey (java.security.PublicKey)7 Test (org.junit.Test)5 JWK (org.keycloak.jose.jwk.JWK)5 OIDCConfigurationRepresentation (org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation)4 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)4 KeyWrapper (org.keycloak.crypto.KeyWrapper)3 CertificateRepresentation (org.keycloak.representations.idm.CertificateRepresentation)3 TestOIDCEndpointsApplicationResource (org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource)3 IOException (java.io.IOException)2 KeyPair (java.security.KeyPair)2 X509Certificate (java.security.cert.X509Certificate)2 List (java.util.List)2 GET (javax.ws.rs.GET)2 NotFoundException (javax.ws.rs.NotFoundException)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)2 NoCache (org.jboss.resteasy.annotations.cache.NoCache)2 OIDCAdvancedConfigWrapper (org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper)2