Connecting to Keycloak client programmatically is not working

339 Views Asked by At

I am using keycloak 22.0.5

I want to create realms and users programmatically.

when connecting with username and password. It works perfectly. I am able to create realms and users from Java but when I want to use the clientId and ClientSecret. I am receiving the exception jakarta.ws.rs.ProcessingException: jakarta.ws.rs.NotFoundException: HTTP 404 Not Found

connecting with username and password:

Keycloak keycloak = KeycloakBuilder.builder()
.serverUrl("http://localhost:8082/")
.realm("master")
.clientId("admin-cli")
.username("user")
.password("bitnami")
.build();

-
-

keycloak.realms().create(realmRep);
//Realm created

connecting with clientId and clientSecret. I've tried with all the commented server URL's.

Keycloak keycloak = KeycloakBuilder.builder()               //.serverUrl("http://localhost:8082/realms/master/protocol/openid-connect/auth")
//.serverUrl("http://localhost:8082/")
//.serverUrl("http://localhost:8082/realms/master")
.serverUrl("http://localhost:8082/auth")
.realm("master")
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.clientId("my-client")
.clientSecret("47d23P4JQk8ZWuNELa3Osxxxxxxxxxxx")
.build();

keycloak.realms().create(realmRep);
//receiving the exception: jakarta.ws.rs.ProcessingException: 
//jakarta.ws.rs.NotFoundException: HTTP 404 Not Found

client configuration in keycloak

Following the documentation: https://www.keycloak.org/docs-api/22.0.5/javadocs/org/keycloak/admin/client/KeycloakBuilder.html

weird fact: they say to use .serverUrl("mykeycloakUrl/auth") when connecting with username and password and It doesn't work for me. It works withouth it as I mentioned above.

Thank you in advance for any comment you can offer!

2

There are 2 best solutions below

0
On BEST ANSWER

The server URL shouldn't differ between the password and the client credentials grant type. Use the http://localhost:8082/ one as it worked. The HTTP 404 error is likely concealing the real problem when you change the server URL back to the aforementioned value.
Take a look at https://www.keycloak.org/docs/latest/server_development/#authenticating-with-a-service-account.
Including the instructions from the docs in case the link breaks:

  1. Make sure the client is configured as follows:

    client_id is a confidential client that belongs to the realm master

    client_id has Service Accounts Enabled option enabled

    client_id has a custom "Audience" mapper

      Included Client Audience: security-admin-console
    
  2. Check that client_id has the role 'admin' assigned in the "Service Account Roles" tab.

0
On

try use in your POM file

  <dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-admin-client-jakarta</artifactId>
    <version>21.1.2</version>
</dependency>