Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching users in Keycloak from Java code

I am using Spring Boot, Keycloak 10, java 8 and keycloak-admin-client jar. I am able to get user, his groups and roles.

When it comes to search I see different search method options for example I could :

 List<UserRepresentation> search = getKeycloakInstance().realm("my-realm").users()
                .search("username");

https://www.keycloak.org/docs-api/10.0/javadocs/org/keycloak/admin/client/resource/UsersResource.html

But what i need to do i to write couple of methods:

  • search by roles (so search users who has some roles)

  • search by groups and group attributes

  • search by text (firstname, lastname, email) in 'contains' manner: mytext

  • search by roles and text

  • search by list of ids (uuids of users)

I dont' see such possibilities in keycloak-admin-client, or it is possible of what else should I use instead of keycloak-admin-client ?

like image 798
michealAtmi Avatar asked Jun 02 '20 09:06

michealAtmi


People also ask

How do I use Keycloak Admin API rest?

To invoke the API you need to obtain an access token with the appropriate permissions. The required permissions are described in the Server Administration Guide. You can obtain a token by enabling authentication for your application using {project_name}; see the Securing Applications and Services Guide.

How do I add a user to a Keycloak using API?

To create a new user account, you will need to send an HTTP POST request to a /users web service endpoint. Please note, that in the request URL, you will need to provide a Realm name under which the new user should be created. If the request is successful, you will get back a 201 Created status code.


Video Answer


1 Answers

Unfortunately, keycloak-admin-client doesn't provide lots of search options.

How to find users by role:

RoleResource roleResource = getKeycloakInstance().realm("realm_name")
                          .roles().get("role_name");  
roleResource.getRoleUserMembers();

How to find all users in the group:

getKeycloakInstance().realm("realm_name").groups().group("your_group").members();

How to find users by username, firstName, lastName, email:

getKeycloakInstance().realm("my-realm").users()
            .search("username", "lastName", "email");

If it's okay for you, try to use Keycloak Admin REST API to get more search opportunities.

like image 127
YuliiaZ Avatar answered Oct 21 '22 12:10

YuliiaZ