Dan
Dan

Reputation: 61

Keycloak - How to check if username and email exists

We want to create Keycloak users programmatically and check before if the username and/or the email address already exists in Keycloak. We are using version 4.4.0.FINAL.

When we create a user programmatically with the Keycloak admin client we're getting the error code 409 (conflict) if the username or the email address is already in use. But we only get one error message in the response (readEntity), namely that the username already exists. The error message doesn't state that the email address is already in use, too.

What is the best way to check if the username and/or the email address already exists in Keycloak?

The goal is to know exactly if an username or an email address already existing or not. And that not only in combination, but also if user A already used the requested username and user B already used the requested mail address.

Upvotes: 6

Views: 22779

Answers (3)

Pramol
Pramol

Reputation: 31

There is one method to check that username is already present.

List<UserRepresentation> search(@QueryParam("username") String username, @QueryParam("exact") Boolean exact);

To check email if pass email in above method then it will not work. It will search for username.

There is no method to check that email is already present or not but there is some workaround that you can use to check email is present or not.

  Integer count(@QueryParam("lastName") String last,
              @QueryParam("firstName") String first,
              @QueryParam("email") String email,
              @QueryParam("username") String username);

Just pass value null for all parameters except email, so it will search for that Email only.

If that email is present then it will return count 1 and if not present then it will return 0.

Upvotes: 0

ch271828n
ch271828n

Reputation: 17597

In 2020, there is a new API (at least a new PR which is merged on June 2020): https://github.com/keycloak/keycloak/pull/6926

Now we can use APIs such as:

List<UserRepresentation> search(@QueryParam("username") String username, @QueryParam("exact") Boolean exact);

Upvotes: 2

cdan
cdan

Reputation: 3576

Check if username and/or email exists with Admin API:

GET /{realm}/users?username=toto&[email protected] 

Then check whether the result is empty. Both username and email query parameters are optional.

More info: https://www.keycloak.org/docs-api/4.4/rest-api/index.html#_users_resource (Look for section Get users.)

There should be a corresponding command with the Admin CLI kcadm.sh.

--EDIT 2020-01-15--

Sadly, the doc for v4.4.0 disappeared from Keycloak website. The closest doc that remains is for v4.8.0: https://www.keycloak.org/docs-api/4.8/rest-api/index.html#_users_resource

Upvotes: 10

Related Questions