在springboot中,Keycloak-admin-client始终返回空值

hk8txs48  于 2022-12-13  发布在  Spring
关注(0)|答案(1)|浏览(188)

我在我的应用程序中使用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()总是返回null??
如果我把realm.getClients()也返回null,但是我的领域“myRealm”中有用户和客户机。

sczxawaw

sczxawaw1#

问题是您从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()));

相关问题