How to use REST API for Keycloak Admin Through Node JS App

Jawad Rashid
9 min readJul 7, 2024

--

Keycloak allows you to add authentication to your applications and services with ease. Keycloak defines its software as:

Keycloak provides user federation, strong authentication, user management, fine-grained authorization, and more.

Table Of Contents

Introduction

In this article I will give an example on how to use REST api for KeyCloak admin.

First example I will use will be using Postman application to log in to Keycloak admin section and perform a GET action on one of the resources available through Keycloak admin.

In next example, I will share code for a Node application on how to authenticate through Keycloak admin client library and get information on users registered with Keycloak.

I will modify the example in the end to showcase how to logout a logged in user to Keycloak using Node.js Admin library. It will be an extension of the last example.

Keycloak Setup

In order to test out the REST api for Keycloak admin we need to first have Keycloak server running. For this article I will setup Keycloak in docker. You can follow along by using the guide here (https://www.keycloak.org/getting-started/getting-started-docker). I am just going to repeat the main steps.

  1. Install Keycloak under Keycloak by running the following command. Here we running development server of Keycloak with standard options with latest version which at the time of writing was 25.0.1. You can explore keycloak documentation for customization.
docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:25.0.1 start-dev

2. Login to Keycloak Admin Console at http://localhost:8080/admin with your username and password in first step which in our case is admin/admin

3. Create realm and user by following the guide I gave here https://www.keycloak.org/getting-started/getting-started-docker

4. Login to the user added by going to http://localhost:8080/realms/myrealm/account

5. Follow the guide and follow the section titled “Secure the first application”

With keycloak up and running we can switch to Postman.

Postman Example

You can find Keycloak Admin REST api documentation here https://www.keycloak.org/docs-api/latest/rest-api/index.html

I might have missed something but I was not able to find clear instructions on Keycloak REST admin documentation on how to get a access token as all REST actions require a access token. This video https://www.youtube.com/watch?v=Xmjlcbt2LGE helped me understand on how to get access token.

I will be using Postman to test REST api. The instructions on how to get access token are:

  1. Create a new request in Postman
  2. Set the REST method as POST
  3. For url set it to http://localhost:8080/realms/master/protocol/openid-connect/token
  4. Go into body section of the request, select x-www-form-urlencoded as body type and add the following key value pairs:
  • key: username, value: admin
    This is your keycloak admin username
  • key: password, value: admin
    Your keycloak admin password
  • key: client_id, value: admin-cli
  • key: grant_type, value: password

5. Here is a screenshot of the request in Postman

These are all the options I described for authentication in Step 3 and Step 4

6. Click Send and in response you will get a json with access_token.

7. As we will need to use this access_token in multiple requests and it expires in a minute. We can either increase the access_token expiry time or use Postman collection variables. Here I choose to use collection variables.

8. In order to use collection variable make sure that you create a collection for your project in Postman and save your Authenticate request which I described above in that collection. You can save a request in collection by using save button on top send button. In my case I saved it under a collection named “Keycloak

9. You can use collection variables by setting them in a request and using these variables in other requests within another request.

10. I will save the access_token in Postman variable named BEARER_TOKEN. Just go to the tests tab in your Authentication tab, and paste in the following code which sets the collection variable BEARER_TOKEN with the access_token received.

pm.test("response is ok",  ()=>{
pm.response.to.have.status(200)
})

var jsonData = JSON.parse(responseBody);

pm.collectionVariables.set("BEARER_TOKEN", jsonData.access_token);

11. Whenever you run the authenticate request in Postman the test given above will run and save the access_token returned in BEARER_TOKEN collection variable.

Now, let’s test some REST actions by looking through the Keycloak REST admin api documentation.

  1. We can look up in documentation that we can get sessions stats for a realm i.e. if there are any logged in users. The documentation for the above action is given below in screenshot taken from Keycloak docs.
Client Sessions Stats Documentation

2. As we can see from the docs that you need to select a realm in the url and it will return stats. Let’s set up a new request for this.

3. Add a new request in the Postman collection for the project (in my case it is named Keycloak).

4. Select REST method as GET

5. Set url as http://localhost:8080/admin/realms/myrealm/client-session-stats (change myrealm in url with the name of your realm you created while setting up Keycloak)

6. This will not work without the access token so go to the authorization tab in your new request.

7. From the dropdown for type of authorization select Bearer Token

8. In the Token field add {{BEARER_TOKEN}} where BEARER_TOKEN is the collection variable we set in authentication request.

9. First login a user you created while setting up Docker my going to the url: http://localhost:8080/realms/myrealm/account and giving username and password for user you created.

10. Now go back to Postman. First run authenticate request in Postman which will set the BEARER_TOKEN with access_token.

11. Now run the client stats request and it will give you an output like below:

[
{
"offline": "0",
"clientId": "account-console",
"active": "1",
"id": "7e8bc9f6-42ac-4265-90f9-ca9219cb484a"
}
]

12. As we have logged in 1 user this shows us that 1 user is logged in and the id of the user.

We can do this again for listing more details for users for a realm by making a request at http://localhost:8080/admin/realms/myrealm/users and it will give a response like below. I got the url by going through Keycloak REST docs.

[
{
"id": "e4c5893b-ce6f-4880-91e0-c68df109480f",
"username": "myuser",
"firstName": "Developer",
"lastName": "Man",
"email": "test@test.com",
"emailVerified": false,
"createdTimestamp": 1719925905091,
"enabled": true,
"totp": false,
"disableableCredentialTypes": [],
"requiredActions": [],
"notBefore": 1719929615,
"access": {
"manageGroupMembership": true,
"view": true,
"mapRoles": true,
"impersonate": true,
"manage": true
}
}
]

You can use this for more actions which are user specific. This the end of the Postman section of using Keycloak. Let’s switch to creating a node application for keycloak REST admin api.

Node.js Keycloak Admin Application

The Node.js application we will create will retrieve all logged in users and terminate session for a single user so they get logged out. Here are the steps:

  1. Searching for Keycloak Admin Node client library I found that there is a node js package https://www.npmjs.com/package/keycloak-connect which helps us to connect to Keycloak Admin.
  2. I will be using the documentation given on their github repo here: https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-admin-client
  3. First select a folder for your node js application and run the following command to install Node JS Keycloak admin client library:
npm install @keycloak/keycloak-admin-client

4. Now create app.js in your project.

5. Import Admin client library on top of your node app

import KcAdminClient from '@keycloak/keycloak-admin-client';

6. The doc states that you can connect to keycloak by using the following code:

// To configure the client, pass an object to override any of these  options:
// {
// baseUrl: 'http://127.0.0.1:8080',
// realmName: 'master',
// requestOptions: {
// /* Fetch request options https://developer.mozilla.org/en-US/docs/Web/API/fetch#options */
// },
// }
const kcAdminClient = new KcAdminClient();

7. In my case I wanted to use localhost instead of 127.0.0.1 as it was not working so I customized the admin library by changing the above code to following code. You can customize more options by looking up available options.

const kcAdminClient = new KcAdminClient({
baseUrl: 'http://localhost:8080'
}
);

8. Next authenticate to keycloak admin by using the code below. These are all the same options we added while authenticating through Postman.

await kcAdminClient.auth({
username: 'admin',
password: 'admin',
grantType: 'admin-cli',
clientId: 'myrealm'
});

9. You can set a default realm for further requests which we will do.

  kcAdminClient.setConfig({
realmName: 'myrealm',
});

10. Let’s just get a list of all clients by following one of the examples in the documentation

  const users = await kcAdminClient.users.find({ first: 0, max: 10 });
console.log(users);

11. You will get a response like below which is same response you got using Postman.

[
{
id: 'e4c5893b-ce6f-4880-91e0-c68df109480f',
username: 'myuser',
firstName: 'Developer',
lastName: 'Man',
email: 'test@test.com',
emailVerified: false,
createdTimestamp: 1719925905091,
enabled: true,
totp: false,
disableableCredentialTypes: [],
requiredActions: [],
notBefore: 1719929615,
access: {
manageGroupMembership: true,
view: true,
mapRoles: true,
impersonate: true,
manage: true
}
}
]

12. Remove the code defined in step 10 for users.find and console.log. Let’s find all logged in users. Looking through the node.js client library and also Keycloak documentation I found out that we can find all logged in users but first we need the client id. In order to do that we will use the following code:

const clients = await kcAdminClient.clients.find({clientId: 'account-console'});

13. Here account-console is the value we need. I found all client id in our app by running a Postman request at http://localhost:8080/admin/realms/myrealm/clients. The response included values of account, account-console, admin-cli, broker, myclient, realm-management, and security-admin-console.

14. After looking at docs I found out that account-console is the value we need to find client id for users.

15. In next step we will list all sessions for users that are logged in. I created two more users by going into http://localhost:8080/admin and creating users. Choose your custom realm myrealm (in my case) before creating users.

16. Log in another user in another browser created in step 15 so you have more than 1 logged in user.

17. List all logged in users by running the code below. Here this functions needs id which is the client id we found om step 12.

const logged_in_users = await kcAdminClient.clients.listSessions({id: clients[0]['id']});

18. Last step is that if there is any logged in user then select 1 user and log them out. Run the following code:

if(logged_in_users.length > 0) {
console.log("Logged out ", logged_in_users[0]['id'], logged_in_users[0]['username'], logged_in_users[0]['userId'])
const response = await kcAdminClient.realms.removeSession({ realm: KEYCLOAK_REALM,sessionId: logged_in_users[0]['id']});
}

19. Now run the app and you will see the username of the user that was logged out. Just go to that user browser tab and refresh and you will see that you are logged out. Go to the other user session and refresh and they should be logged in. This means that our code is running.

By looking at the code in github docs for Node.JS client library and Keycloak admin REST api documentation you can find how to perform actions and what are the required values for that. Hope you found this article useful. I am posting the final code below along with any resources.

Final Code

I added some code to use values from environment variables if you want to use it.

import KcAdminClient from '@keycloak/keycloak-admin-client';

/* Setting Environment and defaults */
const BASE_URL = process.env.BASE_URL || 'http://localhost:8080';
const KEYCLOAK_USERNAME = process.env.KEYCLOAK_USERNAME || 'admin';
const KEYCLOAK_PASSWORD = process.env.KEYCLOAK_PASSWORD || 'admin';
const KEYCLOAK_GRANT_TYPE = process.env.KEYCLOAK_GRANT_TYPE || 'password';
const KEYCLOAK_CLIENT_ID = process.env.KEYCLOAK_CLIENT_ID || 'admin-cli';
const KEYCLOAK_REALM = process.env.KEYCLOAK_REALM || 'myrealm';

const kcAdminClient = new KcAdminClient({
baseUrl: BASE_URL
}
);

await kcAdminClient.auth({
username: KEYCLOAK_USERNAME,
password: KEYCLOAK_PASSWORD,
grantType: KEYCLOAK_GRANT_TYPE,
clientId: KEYCLOAK_CLIENT_ID
});

// List first page of users
kcAdminClient.setConfig({
realmName: KEYCLOAK_REALM,
});

// Find the client id for users. For me following the guide the users created in custom realm had clientId.
// Standard Client Id in dev server below are account, account-console, admin-cli, broker, myclient, realm-management,
// security-admin-console

// This is to get the client id to be used below
const clients = await kcAdminClient.clients.find({clientId: 'account-console'});

// Findings all logged in users for account-console.
const logged_in_users = await kcAdminClient.clients.listSessions({id: clients[0]['id']});
// console.log(logged_in_users);

if(logged_in_users.length > 0) {
console.log("Logged out ", logged_in_users[0]['id'], logged_in_users[0]['username'], logged_in_users[0]['userId'])
const response = await kcAdminClient.realms.removeSession({ realm: KEYCLOAK_REALM,sessionId: logged_in_users[0]['id']});
}

Package.json

{
"type": "module",
"dependencies": {
"@keycloak/keycloak-admin-client": "^25.0.1"
}
}

Resources

  1. Keycloak Docker Setup: https://www.keycloak.org/getting-started/getting-started-docker
  2. Keycloak admin console url: http://localhost:8080/admin
  3. Keycloak user login: http://localhost:8080/realms/myrealm/account
  4. Keycloak REST admin API documentation: https://www.keycloak.org/docs-api/latest/rest-api/index.html
  5. YouTube video on how to use Keycloak REST api in Postman: https://www.youtube.com/watch?v=Xmjlcbt2LGE
  6. Keycloak Node.JS admin client library package: https://www.npmjs.com/package/keycloak-connect
  7. Keycloak Node.JS admin client library github documentation with examples: https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-admin-client

--

--

Jawad Rashid

A data scientist with background in full stack web development. My hobbies include learning new technology and working with mobile game development