Create new user with Java API

Hi there!

I would like to create a new user in the realm “foo” with the Java admin client library.

My connection code looks like this:

val keycloak = Keycloak.getInstance(authServerUrl, "foo", clientId, accessToken)

I have not understood what value should I use for the access token. So I tried two values:

  • JWT access token of the frontend user, with a bearer only client - this results in 403
  • secret of a confidential client - this results in 401

How is this intended to work? Should I use the master realm, with the security-admin-console client, and then use the “foo” realm when creating the user, like so:

val response = keycloak.realm(keyCloakConfig.realm).users().create(keyCloakUser)

Thank you for your answer. I have chosen example 2. Still receiving status 403

My code:

private final val clientId = "backend"
private final val keyCloakConfig = applicationProperties.keyCloak
private final val keycloak = KeycloakBuilder.builder()

val response = keycloak.realm(keyCloakConfig.realm).users().create(keyCloakUser)

It is working now. I needed to add roles on the Service account roles tab: