Skip to content

Instantly share code, notes, and snippets.

@luciddreamz
Forked from paoloantinori/keycloak.sh
Last active July 24, 2024 08:58
Show Gist options
  • Select an option

  • Save luciddreamz/83a888eedd9274b4045a3ab8af064faa to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown
Author

Untested! :)

@victorperin

Copy link
Copy Markdown

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

@ec-wagner

Copy link
Copy Markdown

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
Copy Markdown

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

ghost commented Jul 17, 2019

Copy link
Copy Markdown

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

@jijiechen

jijiechen commented Jul 25, 2019

Copy link
Copy Markdown

@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

aawgit commented Aug 22, 2019

Copy link
Copy Markdown

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

bi40 commented Nov 14, 2019

Copy link
Copy Markdown

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

msca79 commented Jan 29, 2020

Copy link
Copy Markdown

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
Copy Markdown

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
Copy Markdown

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
Copy Markdown

@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
Copy Markdown

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
Copy Markdown

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

@azadious

Copy link
Copy Markdown

Untested! :)

Don't worry it works.

@hendisantika

Copy link
Copy Markdown

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

dawidd6 commented Aug 19, 2022

Copy link
Copy Markdown

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
Copy Markdown

Thank you!
It's worked for me

@Grantismo

Copy link
Copy Markdown

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.

@andersonbosa

andersonbosa commented Jun 17, 2024

Copy link
Copy Markdown

Raw HTTP format:

POST http://localhost:8080/realms/YOUR_REALM/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded

grant_type=password&client_id=admin-cli&username=YOUR_USER&password=YOUR_PASSWORD

Example using defaults:

POST http://localhost:8080/realms/master/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded

grant_type=password&client_id=admin-cli&username=admin&password=admin

@steadyk

steadyk commented Jul 24, 2024

Copy link
Copy Markdown

Just as hint:

We had issues with passwords which contains non ASCII characters.

We were able to fix this by replacing:

-d "password=${KEYCLOAK_CLIENT_SECRET}" \

with

--data-urlencode "password=${KEYCLOAK_CLIENT_SECRET}" \

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