Skip to content

Instantly share code, notes, and snippets.

@luciddreamz
Forked from paoloantinori/keycloak.sh
Last active February 27, 2024 05:26
Show Gist options
  • Star 44 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save luciddreamz/83a888eedd9274b4045a3ab8af064faa to your computer and use it in GitHub Desktop.
Save luciddreamz/83a888eedd9274b4045a3ab8af064faa to your computer and use it in GitHub Desktop.
Keycloak Admin API Rest Example: Get User
#!/bin/bash
# requires https://stedolan.github.io/jq/download/
# config
KEYCLOAK_URL=http://localhost:8080/auth
KEYCLOAK_REALM=realm
KEYCLOAK_CLIENT_ID=clientId
KEYCLOAK_CLIENT_SECRET=clientSecret
USER_ID=userId
export TKN=$(curl -X POST "${KEYCLOAK_URL}/realms/${KEYCLOAK_REALM}/protocol/openid-connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=${KEYCLOAK_CLIENT_ID}" \
-d "password=${KEYCLOAK_CLIENT_SECRET}" \
-d 'grant_type=password' \
-d 'client_id=admin-cli' | jq -r '.access_token')
curl -X GET "${KEYCLOAK_URL}/admin/realms/${KEYCLOAK_REALM}/users/${$USER_ID}" \
-H "Accept: application/json" \
-H "Authorization: Bearer $TKN" | jq .
@luciddreamz
Copy link
Author

Untested! :)

@victorperin
Copy link

Did I must configure something with a client to enable this way of getting the access_token?

@ec-wagner
Copy link

Hi!

Do you know if keyloac can handle the same POST request (to get a token) as JSON instead of form data?

e.g. like this:

curl -X POST http://localhost:8080/auth/realms/master/protocol/openid-connect/token \
   --header "Content-Type: application/json" \
   --data '{"grant_type": "password", "client_id": "admin-cli", "username": "admin", "password": "admin"}'

I am getting the following error:

{"error":"invalid_request","error_description":"Missing form parameter: grant_type"}

Or is "Content-Type: application/x-www-form-urlencoded" header a requirement that can`t be bypassed?

@jijiechen
Copy link

The admin RESTful API has a base path /auth/admin/realms/

Copy link

ghost commented Jul 17, 2019

@jijiechen , so how would a rest api call for token ackquiration look like ?

@jijiechen
Copy link

jijiechen commented Jul 25, 2019

@oe19fyfa For acquiring a token, I didn't test the script provided by the gist author, but I did test the request using Postman, the script here looks good.
Here is a C# code sample for getting an access token:
https://github.com/dotnetclub-net/dotnetclub/blob/dev/src/Discussion.Web/Services/UserManagement/KeyCloakUserUpdater.cs#L66

@aawgit
Copy link

aawgit commented Aug 22, 2019

What I experienced was that the admin user token is given for master realm (Too bad that there is no proper documentation). Therefore the code should be changed as KEYCLOAK_REALM=master. This answer by Boomer is helpful https://stackoverflow.com/questions/48146410/unable-to-get-oauth-token-from-keycloak

@bi40
Copy link

bi40 commented Nov 14, 2019

Hi!

Do you know if keyloac can handle the same POST request (to get a token) as JSON instead of form data?

e.g. like this:

curl -X POST http://localhost:8080/auth/realms/master/protocol/openid-connect/token \
   --header "Content-Type: application/json" \
   --data '{"grant_type": "password", "client_id": "admin-cli", "username": "admin", "password": "admin"}'

I am getting the following error:

{"error":"invalid_request","error_description":"Missing form parameter: grant_type"}

Or is "Content-Type: application/x-www-form-urlencoded" header a requirement that can`t be bypassed?

the content type is required in this example

@msca79
Copy link

msca79 commented Jan 29, 2020

Hi,

There is more "$" in USER_ID

users/${**$**USER_ID}

curl -X GET "${KEYCLOAK_URL}/admin/realms/${KEYCLOAK_REALM}/users/${$USER_ID}" \
-H "Accept: application/json" \
-H "Authorization: Bearer $TKN" | jq .

this is works for me:

curl -X GET "${KEYCLOAK_URL}/admin/realms/${KEYCLOAK_REALM}/users/${USER_ID}" \
-H "Accept: application/json" \
-H "Authorization: Bearer $TKN" | jq .

Anyway works :)

regards, Szabi

@rthummarajula
Copy link

Thanks @jijiechen for below advise, it saved lot of time and it is working fine.

The admin RESTful API has a base path /auth/admin/realms/

@hasnatsaeed
Copy link

Hi,
It seems that when I use my custom realm (xyz) to get the access token for the admin user, it is not working. I have to specify the realm as 'master' to get an access token for admin-cli. Can somebody please help me with this? Why can't I use my own realm (xyz) to get the token for admin user? I can see that under my own realm clients, I do have the admin-cli client available.Thanks

@jijiechen
Copy link

@hasnatsaeed Custom realms mean to manage other systems that consume these custom realms, and only the master realm is meant to manage the KeyCloak itself.
So the situation you ran into was a correct behavior, wasn't it?

@jeudy-ua
Copy link

Is there any way to get the groups in the user detail response? The UserRepresentation definition has the groups field, but is not returned by the api:

 {'id': '314cfd91-dae1-40c1-9af9-5857c6531dc3',
  'createdTimestamp': 1600373234948,
  'username': 'jeudy@x.io',
  'enabled': True,
  'totp': False,
  'emailVerified': True,
  'firstName': 'Jeudy',
  'lastName': 'Blanco',
  'email': 'jeudy@x.io',
  'disableableCredentialTypes': [],
  'requiredActions': [],
  'notBefore': 0,
  'access': {'manageGroupMembership': True,
   'view': True,
   'mapRoles': True,
   'impersonate': True,
   'manage': True}}

@SalahAdDin
Copy link

@jijiechen Thanks man, you gave me a clue about my problem.

@azadious
Copy link

Untested! :)

Don't worry it works.

@hendisantika
Copy link

Is there any way to list all realm & client roles using Java?
For example:

 @GetMapping("/roles")
    public ResponseEntity<List<RoleRepresentation>> getRoles() {
        Keycloak keycloak = getKeycloakInstance();
        ClientRepresentation clientRepresentation = keycloak.realm(keycloakRealm).clients().findByClientId(keycloakClient).get(0);
        List<RoleRepresentation> roles = keycloak.realm(keycloakRealm).clients().get(clientRepresentation.getId()).roles().list();
        return ResponseEntity.ok(roles);
    }

Above code is to list all client roles. I want to list realm roles.

Thanks

@dawidd6
Copy link

dawidd6 commented Aug 19, 2022

If anyone like me will try this script on newer Keycloak and it does not work, see: https://stackoverflow.com/questions/70577004/keycloak-could-not-find-resource-for-full-path

@obervinov
Copy link

Thank you!
It's worked for me

@Grantismo
Copy link

On keycloak 21.0.1 the following works for me:

#!/bin/bash

# requires https://stedolan.github.io/jq/download/

# config
KEYCLOAK_URL=http://localhost:8080 # NOTE: no /auth
KEYCLOAK_REALM=realm
KEYCLOAK_CLIENT_ID=clientId
KEYCLOAK_CLIENT_SECRET=clientSecret
USER_ID=userId

export TKN=$(curl -X POST "${KEYCLOAK_URL}/realms/${KEYCLOAK_REALM}/protocol/openid-connect/token" \
 -H "Content-Type: application/x-www-form-urlencoded" \
 -d "client_id=${KEYCLOAK_CLIENT_ID}" \
 -d "client_secret=${KEYCLOAK_CLIENT_SECRET}" \
 -d 'grant_type=client_credentials' | jq -r '.access_token')

curl -X GET "${KEYCLOAK_URL}/admin/realms/${KEYCLOAK_REALM}/users/${USER_ID}" \
-H "Accept: application/json" \
-H "Authorization: Bearer $TKN" | jq .

In the client config:
Client authentication: On
Direct access grants: On
Service account roles: On

Under "Service Account Roles" assign the manage-users role.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment