简体   繁体   English

Keycloak - 获取所有用户映射到角色

[英]Keycloak - Get all Users mapped to roles

I know keycloak has exposed below api,我知道keycloak已经暴露在api下面,

<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-services</artifactId>
    <version>2.0.0.Final</version>
</dependency>

With complete documentation here .这里有完整的文档。 I cannot find the required api here to fetch all users with specific role mapped to them.我在这里找不到所需的 api 来获取映射到他们的特定角色的所有用户。

Problem Statement - I need to pick all users from keycloak server who have a specific role.问题陈述- 我需要从具有特定角色的 keycloak 服务器中挑选所有用户。 I need to send email to all users with role mapped to them.我需要向所有角色映射到他们的用户发送电子邮件。

There is an outstanding feature request asking for this function via the API.有一个突出的功能请求通过 API 请求此功能。

In the meantime if your requirement is once-off you could obtain the user names (or email addresses) by interrogating the database joining KEYCLOAK_ROLE to USER_ROLE_MAPPING to USER_ENTITY同时,如果您的要求是一次性的,您可以通过询问数据库将 KEYCLOAK_ROLE 加入到 USER_ROLE_MAPPING 到 USER_ENTITY 来获取用户名(或电子邮件地址)

Something like:类似的东西:

SELECT username
FROM keycloak_role kr 
   JOIN user_role_mapping rm ON kr.id = rm.role_id
   JOIN user_entity ue ON rm.user_id = ue.id
WHERE kr.name = 'your_role_name';

Based on the documentation it appears to be this API:根据文档,它似乎是这个 API:

GET /{realm}/clients/{id}/roles/{role-name}/users

It is there for a while.它在那里有一段时间了。 In this older version however it was not possible to get more than 100 users this way.然而,在这个旧版本中,不可能以这种方式获得超过 100 个用户。 It was fixed later and pagination possibility was added.稍后修复并添加了分页功能。

Here is another interesting query, which would also display other useful fields.这是另一个有趣的查询,它还会显示其他有用的字段。

SELECT kr_role.REALM_ID 'Realm', cl.CLIENT_ID 'Realm Client', 
    kr_role.NAME 'Role Name', 
    kr_role.DESCRIPTION 'Role Description', 
    user_ent.USERNAME 'Domain ID', user_ent.EMAIL 'Email'
  FROM keycloak_role kr_role, user_role_mapping role_map, 
    user_entity user_ent, client cl
  WHERE role_map.USER_ID = user_ent.ID
  AND kr_role.ID = role_map.ROLE_ID
  AND kr_role.CLIENT = cl.ID
  AND cl.REALM_ID = '<realm_name>'
  AND cl.CLIENT_ID = '<client_name>'
  ORDER BY 1, 2, 3;

现在应该可以使用更新的休息端点。

Set<UserRepresentation> usersOfRole = realmResource.roles().get(roleName).getRoleUserMembers();

GET /{realm}/clients/{id}/roles/{role-name}/users

SELECT username,
       kr.NAME,
       kr.REALM_ID
FROM KEYCLOAK_ROLE kr
JOIN USER_ROLE_MAPPING rm ON kr.id = rm.role_id
JOIN USER_ENTITY ue ON rm.user_id = ue.id
ORDER BY USERNAME,
         NAME,
         REALM_ID;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM