How to get users by custom attributes in keycloak?

This is not possible by default, but Keycloak offers the possibility to extend its functionalities via a system of Service Provider Interfaces which is very easy to implement.

Here is an example of new route that allows to search by custom attributes :

public class SearchByAttributeResourceProvider implements RealmResourceProvider {
    private KeycloakSession session;

    public SearchByAttributeResourceProvider(KeycloakSession session) {
        this.session = session;
    }

    @Override
    public Object getResource() {
        return this;
    }

    @GET
    @Path("search-by-stuff/{stuffValue}")
    @Produces({MediaType.APPLICATION_JSON})
    public List<UserRepresentation> getUsersByStuff(@PathParam("stuffValue") String stuffValue) {
        return session
                .users()
                .searchForUserByUserAttribute("stuff", stuffValue, session.getContext().getRealm())
                                .stream()  
                                .map(userModel -> ModelToRepresentation.toRepresentation(session, session.getContext().getRealm(), userModel))
                                .collect(toList());
    } 

    @Override
    public void close() {

    }
}

You'll find more details here : https://www.keycloak.org/docs/latest/server_development/index.html#_extensions_rest


This is enabled out of the box from Keycloak version 15.1.0

Using GET /{realm}/users API, parameter q is introduced: A query to search for custom attributes, in the format 'key1:value2 key2:value2'

curl 'http://{{keycloak_url}}/auth/admin/realms/{{realm}}/users?q=phone:123456789'

You can also combine several attributes within this parameter using space ' ' delimiter

curl 'http://{{keycloak_url}}/auth/admin/realms/{{realm}}/users?q=phone:123456789 country:USA'

Docs: https://www.keycloak.org/docs-api/15.1/rest-api/index.html#_users_resource


With latest version of keycloak (18.01), we have api in


    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    List<UserRepresentation> searchByAttributes(@QueryParam("q") String searchQuery);

The query param is of format 'key:value' . Using this we can get list of all users by custom attributes


Current Keycloak API version is 4.8 and there is API: Get users Returns a list of users, filtered according to query parameters

GET /{realm}/users

See doc: https://www.keycloak.org/docs-api/4.8/rest-api/index.html#_users_resource

Only this "search" is available from the API. If you need search by user attributes, then you need to implement it in your own code.

Tags:

Keycloak