Accept self signed certs with the KeycloakAdmin client (java)

I’m using the java KeycloakAdmin client to connect to Keycloak and create a realm/client.
This is my dependency:

    implementation group: 'org.keycloak', name: 'keycloak-admin-client', version: '24.0.0'

I create and use the KeycloakAdmin client like so:

        try (Keycloak keycloakAdmin = KeycloakBuilder.builder()
                .serverUrl(serverUrl)
                .realm(adminRealm)
                .username(username)
                .password(password)
                .clientId(adminClientId)
                .build()) {
             //... do stuff ...
        } catch (Exception e) {
            LOGGER.error("Error initializing Keycloak", e);
        }

The problem is that if Keycloak is running self signed certs then I get SSL Handshake Exceptions.

The KeycloakAdmin client doesn’t seem to have a way to turn off hostname verification or to generally accept self signed certs.

How do I do this?

Ahh, I found the answer:

        KeycloakBuilder keycloakBuilder = KeycloakBuilder.builder()
                .serverUrl(serverUrl)
                .realm(adminRealm)
                .username(username)
                .password(password)
                .clientId(adminClientId);

        if (acceptUntrustedCerts) {
            SSLFactory defaultSslFactory = SSLFactory.builder()
                    .withUnsafeTrustMaterial()
                    .withUnsafeHostnameVerifier()
                    .build();

            keycloakBuilder.resteasyClient(ResteasyClientBuilder.newBuilder()
                    .sslContext(defaultSslFactory.getSslContext())
                    .hostnameVerifier(defaultSslFactory.getHostnameVerifier())
                    .build());
        }
1 Like

I couldn’t find SSLFactory in the answer from @ndtreviv. This is what worked for me:

		KeycloakBuilder keycloakBuilder = KeycloakBuilder.builder()
				.serverUrl(environmentUtils.getKeycloakUrl())
				.realm("master")
				.clientId("admin-cli")
				.grantType(OAuth2Constants.PASSWORD)
				.username(environmentUtils.getKeycloakAdmin())
				.password(environmentUtils.getKeycloakAdminPassword());
		
        if (environmentUtils.isSslTrustSelfSignedCertificate()) {
        	
        	SSLContext sslContext = null;

        	try {
        		
				sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
			
        	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
				throw new RuntimeException(e.getMessage(), e);
			}
        	
            keycloak = keycloakBuilder.resteasyClient(ResteasyClientBuilder.newBuilder().sslContext(sslContext).build()).build();
        }