我在应用程序中使用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,但我有用户和客户端在我的领域" myreal& quot;。
问题是您正在从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()));