Keycloak 用户资源 - 返回具有角色和组的用户表示,而不是查询角色和组的 REST API

问题描述 投票:0回答:2

我必须按文本、组和角色搜索用户,查询每个用户的用户、组和角色需要 6 秒,大约是对 Keycloak REST API 的 15 个 HTTP 请求。

从 GUI 的角度来看,如此缓慢的搜索是不可接受的。您如何使用 Keycloak 搜索项目中的用户?您是否从 Keycloak 同步用户?那么数据就不会是新鲜的..或者也许可以在Keycloak中编写一些适配器来将数据同步到我的应用程序,因此更改将立即反映在我的数据库中,并且我将在我的数据库中搜索用户。 .?或者也许 uconnect 到 Keycloak 数据数据库?但随后你将自己限制在 Keycloak 版本..

当搜索用户时,您会获得 UserResources,并且您可以执行 userResource.toRepresentation() 来获取特定数据,您会看到始终为空的组和角色集合。 是否可以检索已填充组和角色的 UserResources?目前 userResource.toRepresentation() 返回用户,但组和角色为空。那么,如果组和角色集合始终为空,那么 UserRepresentation 中的组和角色集合用于什么?

java spring-boot keycloak
2个回答
3
投票

这不完全是主题,但我需要找到与特定用户关联的角色,并且这个问题首先在我的关键字网络搜索中出现。这是对我有用的 keycloak 客户端 13.0.1

RealmResource realmResource = keycloak.realm(REALM);
UsersResource usersResource = realmResource.users();
UserResource userResource =  usersResource.get(USER_ID);
RoleMappingResource roleMappingResource = userResource.roles();
// either realmLevel or clientLevel
RoleScopeResource roleScopeResource = roleMappingResource.realmLevel();
List<RoleRepresentation> rolesRepresentation = roleScopeResource.listAll();

我在其他地方没有找到它,希望它有用。


0
投票

请注意,对于客户端角色,您必须使用客户端的内部 ID,而不是客户端的名称!

 @Transactional
 public List < UserRepresentation > getMembers() {

    RealmResource realmResource = getRealmResource();
    UsersResource usersResource = realmResource.users();

    List < ClientRepresentation > clients = realmResource.clients().findByClientId(publicClientId);
    ClientRepresentation client = clients.getFirst();

    System.out.printf("Public Client-ID: %s%n", publicClientId);
    System.out.printf("Internal Client-ID: %s%n", client.getId());

    usersResource.list(0, usersResource.count()).forEach(user - > {

    UserResource userResource = usersResource.get(user.getId());

    RoleMappingResource roleMappingResource = userResource.roles();

    RoleScopeResource roleScopeResource = roleMappingResource.clientLevel(client.getId());

    List < RoleRepresentation > rolesRepresentation = roleScopeResource.listEffective();
        System.out.printf("User is '%s' and roles are '%s'.%n", user.getEmail(), rolesRepresentation.toString());
     });
© www.soinside.com 2019 - 2024. All rights reserved.