6

How to use Keycloak Admin REST API

 1 year ago
source link: http://www.mastertheboss.com/keycloak/how-to-use-keycloak-admin-rest-api/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to use Keycloak Admin REST API

10 March 2023 by F.Marchioni

The Keycloak REST Admin API is a Web service Endpoint that allows you to manage Keycloak programmatically. It provides endpoints for creating, updating, and deleting Keycloak entities such as users, groups, clients, roles, and realms. You can use any programming language that supports HTTP requests to interact with the API.

Pre-requisite: If you are new to Keycloak, we recommend checking this article for a quick heads up about Keycloak Identity Manager: Keycloak tutorial for beginners

Getting started with Keycloak Admin API

Keycloak Admin CLI is a Client interface to Keycloak resources. You can find it under the Client section of your Realms under the name “admin-cli”:

keycloak rest APi admin-cli

By using the admin-cli Client you can access and manage Keycloak using the language neutral REST API.

Firstly, as the admin-cli is an OpenID Connect Client, we need to collect a token using the Admin credentials you are using to login to keycloak.

The following bash command extracts in a variable the value of the Token:

export access_token=$(curl --insecure -X POST http://localhost:8080/realms/master/protocol/openid-connect/token --user admin-cli:Psip5UvTO1EXUEwzb15nxLWnwdU1Nlcg -H 'content-type: application/x-www-form-urlencoded' -d 'username=admin&password=admin&grant_type=password' | jq --raw-output '.access_token' )
export access_token=$(curl --insecure -X POST http://localhost:8080/realms/master/protocol/openid-connect/token --user admin-cli:Psip5UvTO1EXUEwzb15nxLWnwdU1Nlcg -H 'content-type: application/x-www-form-urlencoded' -d 'username=admin&password=admin&grant_type=password' | jq --raw-output '.access_token' )

Then, verify that the access_token variable contains the actual Token for the Administrator user:

echo $access_token
eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJIeTZ1OFV6aFk2aVpuRXhSTUJ1QkRmb3V3WnZRaGNHYnJYSC0xb0tZbDJVIn0.eyJleHAiOjE2Nzg0NjM4MjQsImlhdCI6MTY3ODQ2MzIyNCwianRpIjoiMTRlOTEwYWYtMTg5YS00YTczLThiYzUtM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ZXIiLCJzdWIiOiJkNGM3NDIyZC0yZDIzLTQzNjQtOGJjNi05Mjk4MTY3MzhiZmMiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhZG1pbi1jbGkiLCJzZXNzaW9uX3N0YXRlIjoiNmJkNzg4N2ItNzZiYi00Yjc3LWJhYmYtOGM5NmNhMTY5ZGU2IiwiYWNyIjoiMSIsInNjb3BlIjoicHJvZmlsZSBlbWFpbCIsInNpZCI6IjZiZDc4ODdiLTc2YmItNGI3Ny1iYWJmLThjOTZjYTE2OWRlNiIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWRtaW4ifQ.bCOKTedsTjeQvCNUj-YQgIuB4P6LIxnnSoj4M2M1VKPXwegP5aust2r8k2JqHpT63DkYaGJGbqzqzu36lpCgXGJQ7TjPJ5MvL1Zs2POJwE6V2E7HD86uJwPiKhT7nbS4KAkz5bR3iOsTh0QbeeNO7IhD0qxmof6SmeKCkSrzRGw1oldo_9lYP_16plyjNtoBTM4nIf0QREOVe_Jto0utaVpe996YINIDkQu8HNmFp43C_URGKIEqP4MlWpImYu-hr5vr-ol-q_lGaAJ6ov0-uzta7BK5Sj8KkQbCWQIMaoroaEy7QZBqNYViTpxyQoCEtv_bUmlLNVmqG8f1h7OKMQ

Managing Keycloak Realm

Once that you have the Admin Token, we will start managing our Keycloak server. Firstly, we will create another Realm where we will create some Users.

The main reference for Keycloak Admin API is available at: https://www.keycloak.org/docs-api/18.0/rest-api/index.html

To create a new Realm, we need to run a POST to Keycloak Admin URL (http://localhost:8080/admin/realms) with a JSON Body which contains the Realm Name. For example:

curl -X POST -k -g -H "Authorization: Bearer $access_token" "http://localhost:8080/admin/realms" -H "Content-Type: application/json" --data '{"id": "testrealm","realm": "testrealm","accessTokenLifespan": 600,"enabled": true,"sslRequired": "all","bruteForceProtected": true,"loginTheme": "keycloak","eventsEnabled": false,"adminEventsEnabled": false}'
curl -X POST -k -g -H "Authorization: Bearer $access_token" "http://localhost:8080/admin/realms" -H "Content-Type: application/json" --data '{"id": "testrealm","realm": "testrealm","accessTokenLifespan": 600,"enabled": true,"sslRequired": "all","bruteForceProtected": true,"loginTheme": "keycloak","eventsEnabled": false,"adminEventsEnabled": false}'

Notice that we need to include in the Authorization: Bearer Header the Token that we have copied into the $access_token variable.

You can check on the Keycloak console that your Server now includes the Realm “testrealm“:

how to use keycloak rest api

Next, we will add an User to the Realm. The API to add a new User you can execute a POST http://localhost:8080/admin/realms/<realm>/users with a JSON Payload which contains details about the User.

For example, the following curl command will create the user “frank”:

curl -k -X POST http://localhost:8080/admin/realms/testrealm/users -H "Content-Type: application/json" -H "Authorization: Bearer $access_token" --data '{ "username": "frank", "enabled": true, "realmRoles": [ "user", "offline_access" ], "attributes": { "uid": ["4010"], "homedir": ["/home/frank"], "shell": ["/sbin/nologin"] } }'
curl -k -X POST http://localhost:8080/admin/realms/testrealm/users -H "Content-Type: application/json" -H "Authorization: Bearer $access_token" --data '{ "username": "frank", "enabled": true, "realmRoles": [ "user", "offline_access" ], "attributes": { "uid": ["4010"], "homedir": ["/home/frank"], "shell": ["/sbin/nologin"] } }'

Next, verify on the Console that the user is available in the Realm:

keycloak rest

To list Users in your testrealm you can run a GET http://localhost:8080/admin/realms/<realm>/users as follows:

curl -k -X GET http://localhost:8080/admin/realms/testrealm/users -H "Authorization: Bearer "$access_token | jq
curl -k -X GET http://localhost:8080/admin/realms/testrealm/users -H "Authorization: Bearer "$access_token | jq

The above REST API returns the following JSON output:

"id": "d0375203-631f-4c32-8fad-bc4482be3c29",
"createdTimestamp": 1678462584187,
"username": "frank",
"enabled": true,
"totp": false,
"emailVerified": false,
"attributes": {
"uid": [
"4010"
"shell": [
"/sbin/nologin"
"homedir": [
"/home/frank"
"disableableCredentialTypes": [],
"requiredActions": [],
"notBefore": 0,
"access": {
"manageGroupMembership": true,
"view": true,
"mapRoles": true,
"impersonate": true,
"manage": true
{
    "id": "d0375203-631f-4c32-8fad-bc4482be3c29",
    "createdTimestamp": 1678462584187,
    "username": "frank",
    "enabled": true,
    "totp": false,
    "emailVerified": false,
    "attributes": {
      "uid": [
        "4010"
      ],
      "shell": [
        "/sbin/nologin"
      ],
      "homedir": [
        "/home/frank"
      ]
    },
    "disableableCredentialTypes": [],
    "requiredActions": [],
    "notBefore": 0,
    "access": {
      "manageGroupMembership": true,
      "view": true,
      "mapRoles": true,
      "impersonate": true,
      "manage": true
    }
  }

Then, let’s try another command, to modify the password for the user “frank”. The command is PUT http://localhost:8080/admin/realms/<realm>/users/<user-id>/reset-password :

curl -k -X PUT http://localhost:8080/admin/realms/testrealm/users/d0375203-631f-4c32-8fad-bc4482be3c29/reset-password -H "Content-Type: application/json" -H "Authorization: bearer $access_token" --data '{ "type": "password", "temporary": false, "value": "my-new-password" }'
curl -k -X PUT http://localhost:8080/admin/realms/testrealm/users/d0375203-631f-4c32-8fad-bc4482be3c29/reset-password -H "Content-Type: application/json" -H "Authorization: bearer $access_token" --data '{ "type": "password", "temporary": false, "value": "my-new-password" }'

Finally, the command to delete an user is DELETE http://localhost:8080/admin/realms/<realm>/users/<userid> . In our example:

http://localhost:8080/admin/realms/testrealm/users/d0375203-631f-4c32-8fad-bc4482be3c29
http://localhost:8080/admin/realms/testrealm/users/d0375203-631f-4c32-8fad-bc4482be3c29

Conclusion

The Keycloak REST Admin API is handy option to manage Keycloak using any interface or language that supports HTTP requests to interact with the API.

Post Views: 17

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK