Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak - Get all Users mapped to roles

I know keycloak has exposed below 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.

Problem Statement - I need to pick all users from keycloak server who have a specific role. I need to send email to all users with role mapped to them.

like image 726
Ankur Singhal Avatar asked Jul 14 '16 10:07

Ankur Singhal


4 Answers

Based on the documentation it appears to be this 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. It was fixed later and pagination possibility was added.

like image 70
David Hladky Avatar answered Nov 16 '22 14:11

David Hladky


This should be now possible with the updated rest endpoint.

Set<UserRepresentation> usersOfRole = realmResource.roles().get(roleName).getRoleUserMembers();
like image 25
Nirojan Selvanathan Avatar answered Nov 16 '22 16:11

Nirojan Selvanathan


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;
like image 3
Lester Avatar answered Nov 16 '22 16:11

Lester


There is an outstanding feature request asking for this function via the 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

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';
like image 10
shonky linux user Avatar answered Nov 16 '22 16:11

shonky linux user