Keycloak - Get all Users mapped to roles

Ankur Singhal picture Ankur Singhal · Jul 14, 2016 · Viewed 8.2k times · Source

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.

Answer

shonky linux user picture shonky linux user · Aug 5, 2016

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';