# Connecting with Keycloak Admin Rest API

This guide explains how to authenticate with and use the Keycloak Admin REST API from a backend application. It walks through the necessary setup, authentication flow, and execution of a sample API request to list users in a realm.

## **Variables**

Certain parameters must be provided to access the Keycloak Admin REST API successfully. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="border-collapse: collapse; border-color: rgb(0, 0, 0); width: 100%;"><thead><tr><th style="border-color: rgb(0, 0, 0); width: 16.5648%;">**Variable**

</th><th style="border-color: rgb(0, 0, 0); width: 44.3411%;">**Description**

</th><th style="border-color: rgb(0, 0, 0); width: 39.0942%;">**Purpose**

</th></tr></thead><tbody><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`BASE_URL`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">The base URL of the Keycloak server (e.g., <span class="s1">https://your-domain</span>)

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">All admin API requests are made under this URL

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`REALM`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">The realm name used to obtain an admin access token

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">Typically <span class="s1">"master"</span> if accessing all realms, or your target realm

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`CLIENT_ID`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">The client ID configured for admin access (must have sufficient privileges)

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">Authenticates the backend to obtain an access token

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`CLIENT_SECRET`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">The client secret associated with the client

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">Required to authenticate confidential clients

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`ADMIN_USERNAME`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">A Keycloak admin user with the <span class="s1">manage-users</span> or <span class="s1">admin</span> role

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">Used in password grant to fetch an access token

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`ADMIN_PASSWORD`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">The password for the above admin user

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">Used with the username to authenticate

</td></tr></tbody></table>

<span class="s1">These values can be found in the </span>**Keycloak Admin Console**<span class="s1"> under </span>**Clients &gt; \[Your Admin Client\]**<span class="s1"> and </span>**Users &gt; \[Admin User\]**<span class="s1">.</span>

## **Prerequisites**

#### **Install Node.js and NPM**

Check if Node.js is installed:

```
node -v
```

Verify npm installation:

```
npm -v
```

#### **Install Required Package**

We’ll use Axios to make HTTP requests. Install it with:

```
npm install axios
```

## **Code**

Once all prerequisites are set up, create a new file named <span class="s2">admin-api.js</span> and add the following code:

```javascript
const axios = require("axios");

const BASE_URL = "https://your-keycloak-domain";
const REALM = "master";
const CLIENT_ID = "admin-cli";
const ADMIN_USERNAME = "your-admin-username";
const ADMIN_PASSWORD = "your-admin-password";

async function getAccessToken() {
  const response = await axios.post(
    `${BASE_URL}/realms/${REALM}/protocol/openid-connect/token`,
    new URLSearchParams({
      client_id: CLIENT_ID,
      grant_type: "password",
      username: ADMIN_USERNAME,
      password: ADMIN_PASSWORD,
    }),
    {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    }
  );
  return response.data.access_token;
}

async function listUsers() {
  try {
    const token = await getAccessToken();
    const response = await axios.get(
      `${BASE_URL}/admin/realms/${REALM}/users`,
      {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }
    );

    console.log("Users in realm:", response.data);
  } catch (err) {
    console.error("Failed to list users:", err.response?.data || err.message);
  }
}

listUsers();
```

Replace:

- <span class="s1">BASE\_URL</span> with your Keycloak server base URL
- <span class="s1">ADMIN\_USERNAME</span> and <span class="s1">ADMIN\_PASSWORD</span> with your actual admin user credentials
- <span class="s1">REALM</span> with <span class="s1">master</span> (or a custom realm if you configured admin access)

## **Execution**

Open the terminal and navigate to the directory where <span class="s2">admin-api.js</span> is saved. Once in the correct directory, run the script with the command:

```
node admin-api.js
```

If the connection is successful:

1. The script will authenticate using the <span class="s1">password</span> grant type
2. It will retrieve a valid admin access token
3. It will fetch and display the list of users in the specified realm

If an error occurs (such as a 401 unauthorized), double-check your admin credentials and client permissions.