Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get users from Keycloak REST API?

Tags:

keycloak

Hi I'm trying to use the Keycloak API but I don't understand very well how it works. I want to obtain all the users of a realm. So I first obtain a token using this endpoint: /realms/master/protocol/openid-connect/token with this params in the request body:

  • client_id
  • grant_type
  • username
  • password
  • client_secret

The first question is: What client should I use?

Then I call this endpoint: /admin/realms/master/users with the token in the Authorization header, but I get a 403 status code and I don't understand why.

Thanks

like image 418
Pedro Brost Avatar asked Apr 05 '19 12:04

Pedro Brost


People also ask

Does Keycloak have a REST API?

Keycloak comes with a fully functional Admin REST API with all features provided by the Admin Console. To invoke the API you need to obtain an access token with the appropriate permissions.


2 Answers

Generally: 403 = you don't have permissions to perform requested action (to view users in this particular case). You need to define Client Roles (realm-management) for used user/client and assign right role (view-users role in this case):

Keycloak 17+ UI: enter image description here

Or Keycloak 17+ UI - client with Service Accounts Enabled enabled: enter image description here

Keycloak 17- UI: enter image description here

like image 98
Jan Garaj Avatar answered Sep 19 '22 19:09

Jan Garaj


You need two steps

  • first get an access token from the admin-cli client of the master realm

  • second call the admin rest api with the access token, set Bearer as prefix in the Authorization header.

# get an access token
curl -X POST \
  https://<HOST>/auth/realms/master/protocol/openid-connect/token \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'cache-control: no-cache' \
  -d 'grant_type=password&username=<USERNAME>l&password=<PASSWORD>&client_id=admin-cli'

# get all users of gateway realm, use the token from above and use Bearer as prefix
curl -X GET \
  https://<HOST>/auth/admin/realms/gateway/users \
  -H 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkI...' \
  -H 'cache-control: no-cache'
like image 36
Konrad Avatar answered Sep 18 '22 19:09

Konrad