When using Keycloak, you may have noticed that user management is done through the UI provided by Keycloak, which is convenient but often not suitable for use in development. For example, you can’t let end-users go directly to Keycloak’s Admin Console to register. Therefore, it is necessary to APIize these functions, and today we are going to share a method to operate Keycloak through programming.

Introduction to Keycloak Admin Client

All our operations in Keycloak Admin Console have specific Restful APIs, which are collectively called Keycloak Admin REST API. The Keycloak Admin Client is a Java HTTP client wrapper for the Keycloak Admin REST API. We just need to introduce the following dependencies to integrate it.

1
2
3
4
5
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-admin-client</artifactId>
    <version>${version}</version>
</dependency>

Here is a brief mention , the underlying use of JBoss Rest Web Service client Resteasy . JBoss RESTEasy is a framework for developing RESTFul Web services using the Java language . It is an implementation of JAX-RS (Java API for RESTful Web Services) , some of its highlights :

  • no configuration file , based on annotations and Java POJO you can implement RESTful client .
  • Based on JBoss Seam (Java EE upper layer enhancements) programming model .

These only as extended knowledge , unless you deep customization , you do not need to learn it , because Keycloak Admin Client has shielded its steep learning costs , next let’s start using it .

Use of Keycloak Admin Client

The Keycloak Admin REST API is required to place an Bearer Token in the Authorization request header in the request. The access rights of the corresponding API are obtained according to the authority information carried in the Token. So when we use Keycloak Admin Client, we should pay special attention to whether the client you are currently using has access rights. The next example uses it as an example to register a new user.

Creating a new user using the Admin account

The Admin administrator in Master Realm has the highest privileges to manage Keycloak and can do almost anything he wants in Keycloak.

Declare a Keyclock instance according to our configuration.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Keycloak adminCli = KeycloakBuilder.builder()
                 // 服务器地址
                .serverUrl("http://localhost:8011/auth/")
                 // master领域
                .realm("master")
                 // 客户端为 admin-cli  
                .clientId("admin-cli")
                 // 需要我们在该客户端下生成密钥
                .clientSecret("f7da6497-98ee-455a-87ba-158793134e56")
                 // 管理员账户
                .username("admin")
                // 管理员密码 
                .password("admin")
                // 授权方式是密码授权 
                .grantType(OAuth2Constants.PASSWORD)
                .build();

Here the authorization method is Password Authorization, which requires that Direct Access Grants Enabled must be turned on under the Setting option of the client, which means that the admin-cli client can access the user’s username and password, and use them to obtain an access token from the Keycloak server, and then be able to perform further access authorization operations.

How can we register new users?

We can do it like this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
UserRepresentation user = new UserRepresentation();
        user.setUsername("apicreated");
        user.setEnabled(true);

        CredentialRepresentation credentialRepresentation = new CredentialRepresentation();
        credentialRepresentation.setTemporary(false);
        credentialRepresentation.setType(CredentialRepresentation.PASSWORD);
        credentialRepresentation.setValue("123456");

        user.setCredentials(Collections.singletonList(credentialRepresentation));

        RealmResource realm = adminCli.realm("master");

        UsersResource users = realm.users();

        Response response = users.create(user);
        System.out.println("response = " + response.readEntity(String.class));

Here UserRepresentation is the user object, we define a user with the username apicreated and a non-temporary password 123456 and register it to Master Realm.

How do I know about these APIs?

The official documentation for the Admin API is given at the following address.

1
https://www.keycloak.org/docs-api/15.0/rest-api/index.html

This is the documentation you must see to use the Keycloak Admin REST API.

Creating new users with Realm admin users

Master Realm admin accounts don’t bother with these “low-level” operations, so they are usually left to the “minions”. In order to create users in felord.cn Realm, you can give a Master Realm user a role manager-users that creates felord.cn users.

spring

There are many more roles in the red box that you need to understand.

Creating a user for felord.cn using the Master account should be written like this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
        Keycloak adminCli = KeycloakBuilder.builder()
                .serverUrl("http://localhost:8011/auth/")
                .realm("master")
                .clientId("admin-cli")
                .clientSecret("86ef2225-14d4-49b1-908e-2b5e058030cc")
                .username("felordadmin")
                .password("123456")
                .grantType(OAuth2Constants.PASSWORD)
                .build();
        // 创建用户        
        UserRepresentation user = new UserRepresentation();
        user.setUsername("apicreated2");
        user.setEnabled(true);

        CredentialRepresentation credentialRepresentation = new CredentialRepresentation();
        credentialRepresentation.setTemporary(false);
        credentialRepresentation.setType(CredentialRepresentation.PASSWORD);
        credentialRepresentation.setValue("123456");

        user.setCredentials(Collections.singletonList(credentialRepresentation));

        RealmResource realm = adminCli.realm("felord.cn");

        UsersResource users = realm.users();

        Response response = users.create(user);

Creating users with service accounts

Each Realm has a management client called realm-management, which is used to manage the current Realm, and you can enable the service account feature of realm-management by following the configuration below.

spring

This way we can get the access credentials of realm-management directly from the Keycloak server, because realm-management has all the administrative functions, so we can create new users in the name of the client instead of the administrative user, and we are not limited to creating users.

Keycloak’s instantiation code is not quite the same as before.

1
2
3
4
5
6
7
Keycloak adminCli = KeycloakBuilder.builder()
        .serverUrl("http://localhost:8011/auth/")
        .realm("felord.cn")
        .clientId("realm-management")
        .clientSecret("38836e47-2c82-4412-a858-9be2a35aa366")
        .grantType(OAuth2Constants.CLIENT_CREDENTIALS)
        .build();

The authorization mode here is different from user behavior, it is client behavior, so grant_type is changed to client mode.

Summary

Creating a user is the same as the previous two methods, you can create a user to try, and there are other APIs that can be implemented in this way. Today, we introduced how to call the Keycloak Admin REST API, which allows you to perform some administrative operations on Keycloak in code. It should be noted that these operations are closely related to the role of the subject of the current operation. There will be space later for a brief introduction to the administrative roles in Keycloak.

Reference https://felord.cn/keycloak6.html