keycloak-admin-client 在 springboot 中总是 returns null

Keycloak-admin-client always returns null in springboot

我在我的应用程序中使用 keycloak 管理客户端

    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-admin-client</artifactId>
        <version>${keycloak.version}</version>
    </dependency>

在我的代码中我有:

package br.com.fabioebner.api.serivce;

import lombok.extern.slf4j.Slf4j;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class KeycloakService {
    private final RealmRepresentation realm;
    private final Keycloak keycloak;

    public KeycloakService() {
        this.keycloak = Keycloak.getInstance(
                "https://myIp/auth/",
                "master",
                "admin",
                "password",
                "admin-cli");
        this.realm = keycloak.realm("myRealm").toRepresentation();
    }

    @EventListener(ApplicationReadyEvent.class)
    public void addUser(){
        List<UserRepresentation> users = realm.getUsers();
        users.forEach(user -> {
            log.debug(user.getUsername());
        });
    }
}

为什么 realm.getUsers() 总是 returns 为空??

如果我也将 realm.getClients() returns 设为 null,但我的领域“myRealm”中有用户和客户。

问题是您从 Realm 表示

获取用户
this.realm = keycloak.realm("myRealm").toRepresentation()

试图从 Realm 获取它们,即:

UsersResource usersResource = keycloak.realm("myRealm").users();
...
List<UserRepresentation> users = usersResource.list();     
users.forEach(u -> System.out.println(u.getUsername()));