How to get Keycloak users via REST without admin account

Borja Canseco picture Borja Canseco · Sep 28, 2017 · Viewed 22.7k times · Source

Is there a way to get a list of users on a Keycloak realm via REST WITHOUT using an admin account? Maybe some sort of assignable role from the admin console? Looking for any ideas.

Right now I'm using admin credentials to grab an access token, then using that token to pull users from the realm/users endpoint.

Getting the token (from node.js app via request):

uri: `${keycloakUri}/realms/master/protocol/openid-connect/token`,
form: {
  grant_type: 'password',
  client_id: 'admin-cli',
  username: adminUsername,
  password: adminPassword,
}

Using the token:

uri: `${keycloakUri}/admin/realms/${keycloakRealm}/users`,
headers: {
  'authorization': `bearer ${passwordGrantToken}`,
}

I want to be able to use generic user info (usernames, emails, fullnames) from a client application.

Answer

Xtreme Biker picture Xtreme Biker · Oct 4, 2017

You need to assign the view-users role from the realm-management client, for the desired user. That would be the configuration for the user:

enter image description here

Then you can grab all the users from the ${keycloakUri}/admin/realms/${keycloakRealm}/users endpoint. That's the info retrieved from the enpoint, accesed via Postman:

enter image description here

Also, unrelated to the asked question, I strongly encourage you not to use grant_type=password unless you absolutelly need to. From the keycloak blog:

RESULT=`curl --data "grant_type=password&client_id=curl&username=user&password=password" http://localhost:8180/auth/realms/master/protocol/openid-connect/token`

This is a bit cryptic and luckily this is not how you should really be obtaining tokens. Tokens should be obtained by web applications by redirecting to the Keycloak login page. We're only doing this so we can test the service as we don't have an application that can invoke the service yet. Basically what we are doing here is invoking Keycloaks OpenID Connect token endpoint with grant type set to password which is the Resource Owner Credentials flow that allows swapping a username and a password for a token.

See also the Oauth2 spec.