javakeycloak

Java, Keycloak: How to programatically create a Realm and set userProfile attributes in it


I'm using Java 21 and Keycloak 25.0.1

I have this realm-config.json file that I want to generate programatically:

{
  "realm": "test",
  "id": "test",
  "enabled": true,
  "userProfile": {
    "attributes": {
      "unmanagedAttributePolicy": ENABLED
    }
  }
}

To do that, I have this code that creates a realm in Keycloak:

var realm = "test"
var realmRepresentation = new RealmRepresentation();
realmRepresentation.setRealm(realm);
        realmRepresentation.setId(realm);
        realmRepresentation.setEnabled(true);


// How do I set the userProfile attribute?
keycloak.get()
   .realms()
   .create(realmRepresentation);

How can I add the configuration for the userProfile? I was not able to find anything useful in the RealmRepresentation docs: https://www.keycloak.org/docs-api/latest/javadocs/org/keycloak/representations/idm/RealmRepresentation.html

I'm not really sure what else I could try doing. Is this not possible programatically? Am I perhaps missing something obvious?

Thank you in advance for any help regarding this :)


Solution

  • You can do something like this:

    final var upConfig = new UPConfig(); 
    upConfig.setUnmanagedAttributePolicy(UnmanagedAttributePolicy.ENABLED);
    keycloak_client.realm(realm).users().userProfile().update(upConfig);
    

    Check this out PUT /admin/realms/{realm}/users/profile in the rest api docs: https://www.keycloak.org/docs-api/26.0.7/rest-api/

    This is the pr for unmanaged attributes are managed: https://github.com/keycloak/keycloak/pull/24937