使用keycloak-admin-client lib
maven
<dependency> <groupId>org.keycloak</groupId> <artifactId>keycloak-admin-client</artifactId> <version>12.0.4</version> </dependency>
Keycloak keycloak = Keycloak.getInstance(keycloakserverurl, "master", "admin", "PASSWORD", "demoapp"); RealmRepresentation realm = keycloak.realm("master").toRepresentation() ; // create a user UserRepresentation userRepresentation = new UserRepresentation(); userRepresentation.setUsername("ccc"); userRepresentation.setFirstName("first name"); userRepresentation.setEmail("ddd@ccc"); // userRepresentation.setRequiredActions(Collections.emptyList()); userRepresentation.setEnabled(true); CredentialRepresentation credentialRepresentation = new CredentialRepresentation(); credentialRepresentation.setType(CredentialRepresentation.PASSWORD); credentialRepresentation.setValue("1234"); userRepresentation.setCredentials(Collections.singletonList(credentialRepresentation)); Response response = keycloak.realm("master").users().create(userRepresentation); System.out.println("response status: " + response.getStatus());
參考
https://www.keycloak.org/docs/latest/server_development/