### Keycloak Admin Client Installation Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/index Install the Keycloak Admin Client using npm. ```APIDOC ## Install ```bash npm install @keycloak/keycloak-admin-client ``` ``` -------------------------------- ### Keycloak Admin Client Usage Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/index Examples demonstrating how to initialize, authenticate, and use the Keycloak Admin Client to manage resources. ```APIDOC ## Usage ### Initialization and Configuration ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; // Default configuration const kcAdminClient = new KcAdminClient(); // Override options const kcAdminClientWithOptions = new KcAdminClient({ baseUrl: 'http://127.0.0.1:8080', realmName: 'master', requestOptions: { /* Fetch request options */ }, }); ``` ### Authentication **Using username and password:** ```javascript await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli', totp: '123456', // optional }); ``` **Using client credentials:** ```javascript const credentials = { grantType: 'client_credentials', clientId: 'clientId', clientSecret: 'some-client-secret-uuid', }; await kcAdminClient.auth(credentials); ``` ### Managing Resources **List users:** ```javascript // List first page of users const users = await kcAdminClient.users.find({ first: 0, max: 10 }); // Find users by attributes const usersByAttribute = await kcAdminClient.users.find({ q: "phone:123" }); ``` **Change realm for subsequent requests:** ```javascript // Override client configuration for all further requests: kcAdminClient.setConfig({ realmName: 'another-realm', }); // This operation will now be performed in 'another-realm' const groups = await kcAdminClient.groups.find(); ``` **Perform a single operation in a specific realm:** ```javascript // Set a `realm` property to override the realm for only a single operation. await kcAdminClient.users.create({ realm: 'a-third-realm', username: 'username', email: 'user@example.com', }); ``` ### Token Refresh **Using `node-openid-client` for token refresh:** ```javascript import { Issuer } from 'openid-client'; const keycloakIssuer = await Issuer.discover('http://localhost:8080/realms/master'); const client = new keycloakIssuer.Client({ client_id: 'admin-cli', token_endpoint_auth_method: 'none', }); // Use the grant type 'password' let tokenSet = await client.grant({ grant_type: 'password', username: 'admin', password: 'admin', }); // Periodically refresh token setInterval(async () => { const refreshToken = tokenSet.refresh_token; tokenSet = await client.refresh(refreshToken); kcAdminClient.setAccessToken(tokenSet.access_token); }, 58 * 1000); // 58 seconds ``` **Refreshing token using `kcAdminClient.auth` (for flows without refresh token):** ```javascript const credentials = { grantType: 'client_credentials', clientId: 'clientId', clientSecret: 'some-client-secret-uuid', }; await kcAdminClient.auth(credentials); setInterval(() => kcAdminClient.auth(credentials), 58 * 1000); // 58 seconds ``` ``` -------------------------------- ### Start Keycloak Server for Testing Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=dependents Command to start the Keycloak server, typically for development or testing purposes. Ensures an admin user with specific credentials exists. ```bash pnpm server:start ``` -------------------------------- ### Build and Run Tests for Keycloak Admin Client Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/index Instructions for building the project, starting the Keycloak server, and running the tests. This is useful for developers contributing to the library or verifying its functionality. ```bash # To build the source do a build: pnpm build # Start the Keycloak server: pnpm server:start # If you started your container manually make sure there is an admin user named 'admin' with password 'admin'. Then start the tests with: pnpm test ``` -------------------------------- ### Run Keycloak Admin Client Tests Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=dependents Command to execute the test suite for the Keycloak Admin Client after building the source and starting the Keycloak server. ```bash pnpm test ``` -------------------------------- ### Build and Run Tests for Keycloak Admin Client Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=dependencies Provides commands to build the project, start the Keycloak server, and run the tests. This is useful for developers contributing to or testing the Keycloak Admin Client library. ```bash pnpm build pnpm server:start pnpm test ``` -------------------------------- ### Build and Run Keycloak Admin Client Tests Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=readme Provides commands to build the project, start a Keycloak server (assuming a pre-configured admin user), and run the associated tests. This is useful for developers contributing to or verifying the functionality of the library. ```bash pnpm build pnpm server:start pnpm test ``` -------------------------------- ### Component Management API Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/index Manage components, which are supported for user federation. Includes create, list, get, update, and delete operations. ```APIDOC ## POST /{realm}/components ### Description Create a new component. ### Method POST ### Endpoint `/{realm}/components` ## GET /{realm}/components ### Description List all components. ### Method GET ### Endpoint `/{realm}/components` ## GET /{realm}/components/{id} ### Description Get a specific component by its ID. ### Method GET ### Endpoint `/{realm}/components/{id}` ## PUT /{realm}/components/{id} ### Description Update an existing component. ### Method PUT ### Endpoint `/{realm}/components/{id}` ## DELETE /{realm}/components/{id} ### Description Delete a component by its ID. ### Method DELETE ### Endpoint `/{realm}/components/{id}` ``` -------------------------------- ### Install Keycloak Admin Client Source: https://context7.com/context7/npmjs_package_keycloak_keycloak-admin-client/llms.txt Install the Keycloak Admin Client package using npm. This is the first step to integrating Keycloak administration into your application. ```bash npm install @keycloak/keycloak-admin-client ``` -------------------------------- ### User Role Mapping API Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=code Endpoints for managing user role mappings, including getting role mappings, adding realm-level role mappings, deleting role mappings, getting available roles, and getting composite roles. ```APIDOC ## GET /{realm}/users/{id}/role-mappings ### Description Gets user role-mappings. ### Method GET ### Endpoint /{realm}/users/{id}/role-mappings ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The ID of the user. ### Response #### Success Response (200) - Returns role mapping information for the user. ## POST /{realm}/users/{id}/role-mappings/realm ### Description Adds realm-level role mappings to the user. ### Method POST ### Endpoint /{realm}/users/{id}/role-mappings/realm ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The ID of the user. ### Request Body - **roles** (array) - Required - An array of role objects to map to the user. ### Response #### Success Response (204) - No content is returned. ## GET /{realm}/users/{id}/role-mappings/realm ### Description Gets realm-level role mappings. ### Method GET ### Endpoint /{realm}/users/{id}/role-mappings/realm ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The ID of the user. ### Response #### Success Response (200) - Returns an array of realm-level role objects mapped to the user. ## DELETE /{realm}/users/{id}/role-mappings/realm ### Description Deletes realm-level role mappings. ### Method DELETE ### Endpoint /{realm}/users/{id}/role-mappings/realm ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The ID of the user. ### Request Body - **roles** (array) - Required - An array of role objects to unmap from the user. ### Response #### Success Response (204) - No content is returned. ## GET /{realm}/users/{id}/role-mappings/realm/available ### Description Gets realm-level roles that can be mapped. ### Method GET ### Endpoint /{realm}/users/{id}/role-mappings/realm/available ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The ID of the user. ### Response #### Success Response (200) - Returns an array of realm-level role objects available to be mapped to the user. ## GET /{realm}/users/{id}/role-mappings/realm/composite ### Description Gets effective realm-level role mappings. This will recurse all composite roles to get the result. ### Method GET ### Endpoint /{realm}/users/{id}/role-mappings/realm/composite ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The ID of the user. ### Response #### Success Response (200) - Returns an array of effective realm-level role objects mapped to the user (including composite roles). ``` -------------------------------- ### Manage Keycloak Required Actions with JavaScript Source: https://context7.com/context7/npmjs_package_keycloak_keycloak-admin-client/llms.txt Demonstrates how to manage required actions for user authentication using the keycloak-admin-client. This includes getting all required actions, specific actions, updating them, registering new ones, and managing their priority. It also shows how to delete actions. The primary dependency is the '@keycloak/keycloak-admin-client' library. ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; const kcAdminClient = new KcAdminClient(); await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli' }); try { // Get all required actions const requiredActions = await kcAdminClient.authenticationManagement.getRequiredActions(); console.log('Required actions:', requiredActions.map(a => a.alias)); // Get specific required action const updatePasswordAction = await kcAdminClient.authenticationManagement.getRequiredAction({ alias: 'UPDATE_PASSWORD' }); // Update required action await kcAdminClient.authenticationManagement.updateRequiredAction( { alias: 'UPDATE_PASSWORD' }, { ...updatePasswordAction, enabled: true, defaultAction: false, priority: 10 } ); // Get unregistered required actions const unregistered = await kcAdminClient.authenticationManagement.getUnregisteredRequiredActions(); // Register a new required action if (unregistered.length > 0) { await kcAdminClient.authenticationManagement.registerRequiredAction({ providerId: unregistered[0].providerId, name: unregistered[0].name }); } // Raise priority of required action await kcAdminClient.authenticationManagement.raiseRequiredActionPriority({ alias: 'VERIFY_EMAIL' }); // Lower priority of required action await kcAdminClient.authenticationManagement.lowerRequiredActionPriority({ alias: 'UPDATE_PASSWORD' }); // Delete required action await kcAdminClient.authenticationManagement.deleteRequiredAction({ alias: 'terms_and_conditions' }); } catch (error) { console.error('Required action operation failed:', error.message); } ``` -------------------------------- ### Monitor and Manage Keycloak Client Sessions (JavaScript) Source: https://context7.com/context7/npmjs_package_keycloak_keycloak-admin-client/llms.txt Provides examples for retrieving active and offline user sessions for a specific client in Keycloak, as well as getting session counts. Requires authentication and a valid client ID. Useful for monitoring user activity. ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; const kcAdminClient = new KcAdminClient(); await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli' }); try { // Find client const clients = await kcAdminClient.clients.find({ clientId: 'my-app' }); const client = clients[0]; // Get active user sessions for client const sessions = await kcAdminClient.clients.listSessions({ id: client.id, first: 0, max: 100 }); console.log(`Active sessions: ${sessions.length}`); sessions.forEach(session => { console.log(`Session ID: ${session.id}, User: ${session.username}, Started: ${new Date(session.start)}`); }); // Get offline sessions const offlineSessions = await kcAdminClient.clients.listOfflineSessions({ id: client.id, first: 0, max: 100 }); // Get session count const sessionCount = await kcAdminClient.clients.getSessionCount({ id: client.id }); console.log(`Total session count: ${sessionCount}`); // Get offline session count const offlineCount = await kcAdminClient.clients.getOfflineSessionCount({ id: client.id }); console.log(`Offline sessions: ${offlineCount}`); } catch (error) { console.error('Session query failed:', error.message); } ``` -------------------------------- ### Token Refresh with openid-client Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=versions Example of how to refresh the access token using an OpenID client like panva/node-openid-client. ```APIDOC ## Token Refresh with openid-client To refresh the access token provided by Keycloak, an OpenID client like panva/node-openid-client can be used like this: ```javascript import {Issuer} from 'openid-client'; const keycloakIssuer = await Issuer.discover( 'http://localhost:8080/realms/master', ); const client = new keycloakIssuer.Client({ client_id: 'admin-cli', // Same as `clientId` passed to client.auth()` token_endpoint_auth_method: 'none', // to send only client_id in the header }); // Use the grant type 'password' let tokenSet = await client.grant({ grant_type: 'password', username: 'admin', password: 'admin', }); // Periodically using refresh_token grant flow to get new access token here setInterval(async () => { const refreshToken = tokenSet.refresh_token; tokenSet = await client.refresh(refreshToken); kcAdminClient.setAccessToken(tokenSet.access_token); }, 58 * 1000); // 58 seconds ``` In cases where you don't have a refresh token, eg. in a client credentials flow, you can simply call `kcAdminClient.auth` to get a new access token, like this: ```javascript const credentials = { grantType: 'client_credentials', clientId: 'clientId', clientSecret: 'some-client-secret-uuid', }; await kcAdminClient.auth(credentials); setInterval(() => kcAdminClient.auth(credentials), 58 * 1000); // 58 seconds ``` ``` -------------------------------- ### Component Management API Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=code Manage components, which are supported for user federation. Includes creation, listing, retrieval, update, and deletion. ```APIDOC ## POST /{realm}/components ### Description Create a new component. ### Method POST ### Endpoint `/{realm}/components` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. #### Request Body - **component** (object) - Required - The component configuration. ### Response #### Success Response (200) - **message** (string) - Success message. ``` ```APIDOC ## GET /{realm}/components ### Description List all components in a realm. ### Method GET ### Endpoint `/{realm}/components` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. ### Response #### Success Response (200) - **components** (array) - An array of component objects. ``` ```APIDOC ## GET /{realm}/components/{id} ### Description Get a specific component by its ID. ### Method GET ### Endpoint `/{realm}/components/{id}` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The component ID. ### Response #### Success Response (200) - **component** (object) - The component object. ``` ```APIDOC ## PUT /{realm}/components/{id} ### Description Update a specific component. ### Method PUT ### Endpoint `/{realm}/components/{id}` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The component ID. #### Request Body - **component** (object) - Required - The updated component configuration. ### Response #### Success Response (200) - **message** (string) - Success message. ``` ```APIDOC ## DELETE /{realm}/components/{id} ### Description Delete a specific component. ### Method DELETE ### Endpoint `/{realm}/components/{id}` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The component ID. ### Response #### Success Response (200) - **message** (string) - Success message. ``` -------------------------------- ### Keycloak Admin Client Usage Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=readme Demonstrates how to initialize and use the Keycloak Admin Client for authentication and performing administrative tasks. ```APIDOC ## Usage ### Initialization ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; // Default configuration // const kcAdminClient = new KcAdminClient(); // Custom configuration const kcAdminClient = new KcAdminClient({ baseUrl: 'http://127.0.0.1:8080', realmName: 'master', requestOptions: { /* Fetch request options */ }, }); ``` ### Authentication **By Username/Password:** ```javascript await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli', totp: '123456', // Optional OTP }); ``` **By Client Credentials:** ```javascript const credentials = { grantType: 'client_credentials', clientId: 'clientId', clientSecret: 'some-client-secret-uuid', }; await kcAdminClient.auth(credentials); ``` ### Operations **List Users:** ```javascript const users = await kcAdminClient.users.find({ first: 0, max: 10 }); ``` **Find Users by Attribute:** ```javascript const users = await kcAdminClient.users.find({ q: "phone:123" }); ``` **Change Realm Configuration:** ```javascript // Override client configuration for all further requests: ncAdminClient.setConfig({ realmName: 'another-realm', }); // This operation will now be performed in 'another-realm' const groups = await kcAdminClient.groups.find(); ``` **Perform Operation in a Specific Realm:** ```javascript // Set a `realm` property to override the realm for only a single operation. await kcAdminClient.users.create({ realm: 'a-third-realm', username: 'username', email: 'user@example.com', }); ``` ``` -------------------------------- ### Token Refresh with OpenID Client Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=readme Example of how to refresh the access token using an OpenID client like panva/node-openid-client. ```APIDOC ## Token Refresh with OpenID Client ```javascript import { Issuer } from 'openid-client'; const keycloakIssuer = await Issuer.discover( 'http://localhost:8080/realms/master', ); const client = new keycloakIssuer.Client({ client_id: 'admin-cli', token_endpoint_auth_method: 'none', }); // Use the grant type 'password' let tokenSet = await client.grant({ grant_type: 'password', username: 'admin', password: 'admin', }); // Periodically using refresh_token grant flow to get new access token setInterval(async () => { const refreshToken = tokenSet.refresh_token; tokenSet = await client.refresh(refreshToken); kcAdminClient.setAccessToken(tokenSet.access_token); }, 58 * 1000); // 58 seconds ``` ``` -------------------------------- ### Components Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=versions Manage components, which are supported for user federation. This includes creating, listing, retrieving, updating, and deleting components. ```APIDOC ## Components ### Create a component * **Method:** POST * **Endpoint:** `/{realm}/components` * **Description:** Creates a new component, typically used for user federation. ### List components * **Method:** GET * **Endpoint:** `/{realm}/components` * **Description:** Retrieves a list of all components in the realm. ### Get a component * **Method:** GET * **Endpoint:** `/{realm}/components/{id}` * **Description:** Retrieves a specific component by its ID. ### Update a component * **Method:** PUT * **Endpoint:** `/{realm}/components/{id}` * **Description:** Updates an existing component by its ID. ### Delete a component * **Method:** DELETE * **Endpoint:** `/{realm}/components/{id}` * **Description:** Deletes a specific component by its ID. ``` -------------------------------- ### Component API Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client Manage components in Keycloak, supported for user federation. Includes creation, listing, retrieval, update, and deletion of components. ```APIDOC ## POST /{realm}/components ### Description Create a new component. ### Method POST ### Endpoint `/{realm}/components` ### Parameters #### Path Parameters - **realm** (string) - Required - The name of the realm. #### Request Body - **component** (object) - Required - The component object to create. - **name** (string) - Required - The name of the component. - **providerType** (string) - Required - The type of provider (e.g., 'org.keycloak.storage.UserStorageProvider'). ``` -------------------------------- ### Initialize and Authenticate KcAdminClient (Password Grant) Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client Demonstrates how to initialize the Keycloak Admin Client and authenticate using username and password with optional TOTP. It shows how to list users and find them by attributes. ```typescript import KcAdminClient from '@keycloak/keycloak-admin-client'; // 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(); // Authorize with username / password await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli', totp: '123456', // optional Time-based One-time Password if OTP is required in authentication flow }); // List first page of users const users = await kcAdminClient.users.find({ first: 0, max: 10 }); // find users by attributes const users = await kcAdminClient.users.find({ q: "phone:123" }); ``` -------------------------------- ### Keycloak Role Management - CRUD Operations (JavaScript) Source: https://context7.com/context7/npmjs_package_keycloak_keycloak-admin-client/llms.txt Provides examples for creating, listing, finding, updating, and deleting realm-level roles in Keycloak. Authentication with the admin client is required. ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; const kcAdminClient = new KcAdminClient(); await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli' }); try { // Create realm role await kcAdminClient.roles.create({ name: 'super-admin', description: 'Super administrator with full access', attributes: { priority: ['high'] } }); // List all realm roles const realmRoles = await kcAdminClient.roles.find(); // Find role by name const role = await kcAdminClient.roles.findOneByName({ name: 'super-admin' }); // Update role await kcAdminClient.roles.updateByName( { name: 'super-admin' }, { description: 'Updated: Super administrator role', attributes: { priority: ['critical'] } } ); // Get users in role const usersInRole = await kcAdminClient.roles.findUsersWithRole({ name: 'super-admin', first: 0, max: 100 }); // Delete role await kcAdminClient.roles.delByName({ name: 'super-admin' }); console.log('Role operations completed'); } catch (error) { console.error('Role operation failed:', error.message); } ``` -------------------------------- ### Initialize and Authenticate Keycloak Admin Client Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=dependencies Demonstrates how to initialize the Keycloak Admin Client and authenticate using username and password, including optional Time-based One-time Password (TOTP). It also shows how to list users and change client configuration. ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; // 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(); // Authorize with username / password await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli', totp: '123456', // optional Time-based One-time Password if OTP is required in authentication flow }); // List first page of users const users = await kcAdminClient.users.find({ first: 0, max: 10 }); // find users by attributes const users = await kcAdminClient.users.find({ q: "phone:123" }); // Override client configuration for all further requests: ncAdminClient.setConfig({ realmName: 'another-realm', }); // This operation will now be performed in 'another-realm' if the user has access. const groups = await kcAdminClient.groups.find(); // Set a `realm` property to override the realm for only a single operation. // For example, creating a user in another realm: await kcAdminClient.users.create({ realm: 'a-third-realm', username: 'username', email: 'user@example.com', }); ``` -------------------------------- ### Authenticate with Client Credentials and Refresh Token Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=dependencies Shows how to authenticate the Keycloak Admin Client using the client credentials grant type. It also includes an example of how to periodically re-authenticate to refresh the access token. ```javascript const credentials = { grantType: 'client_credentials', clientId: 'clientId', clientSecret: 'some-client-secret-uuid', }; await kcAdminClient.auth(credentials); setInterval(() => kcAdminClient.auth(credentials), 58 * 1000); // 58 seconds ``` -------------------------------- ### Keycloak Authentication with Client Credentials Grant Source: https://context7.com/context7/npmjs_package_keycloak_keycloak-admin-client/llms.txt Authenticates a service or application using the client credentials grant type. This is suitable for machine-to-machine communication and requires client ID and client secret. It includes an example of setting up periodic token refresh. ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; const kcAdminClient = new KcAdminClient({ baseUrl: 'https://keycloak.example.com', realmName: 'production' }); const credentials = { grantType: 'client_credentials', clientId: 'backend-service', clientSecret: 'a3f8b927-4c5d-4e9a-b8f3-7d2e1c9a8b7c' }; try { await kcAdminClient.auth(credentials); // Refresh token periodically (every 58 seconds) setInterval(async () => { try { await kcAdminClient.auth(credentials); console.log('Token refreshed'); } catch (error) { console.error('Token refresh failed:', error.message); } }, 58 * 1000); } catch (error) { console.error('Client credentials auth failed:', error.message); } ``` -------------------------------- ### Keycloak Admin Client Usage Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=versions Demonstrates how to initialize and use the Keycloak Admin Client for authentication and basic operations like finding users. ```APIDOC ## Usage ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; // 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(); // Authorize with username / password await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli', totp: '123456', // optional Time-based One-time Password if OTP is required in authentication flow }); // List first page of users const users = await kcAdminClient.users.find({ first: 0, max: 10 }); // find users by attributes const users = await kcAdminClient.users.find({ q: "phone:123" }); // Override client configuration for all further requests: cnc // kcAdminClient.setConfig({ // realmName: 'another-realm', // }); // This operation will now be performed in 'another-realm' if the user has access. // const groups = await kcAdminClient.groups.find(); // Set a `realm` property to override the realm for only a single operation. // For example, creating a user in another realm: // await kcAdminClient.users.create({ // realm: 'a-third-realm', // username: 'username', // email: 'user@example.com', // }); ``` ``` -------------------------------- ### Initialize and Authorize Keycloak Admin Client Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=dependents Demonstrates how to initialize the Keycloak Admin Client and authorize using username and password. It shows how to set default configuration options and handle optional Time-based One-time Password (TOTP). ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; // 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(); // Authorize with username / password await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli', totp: '123456', // optional Time-based One-time Password if OTP is required in authentication flow }); ``` -------------------------------- ### Components Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=dependents Manage components, which are supported for user federation. Supports creation, listing, retrieval, update, and deletion. ```APIDOC ## POST /{realm}/components ### Description Create a new component. ### Method POST ### Endpoint `/{realm}/components` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. #### Request Body - **component** (object) - Required - The component configuration. - **name** (string) - Required - The name of the component. - **providerId** (string) - Required - The ID of the provider. - **providerType** (string) - Required - The type of the provider (e.g., "org.keycloak.storage.UserStorageProvider"). - **config** (object) - Optional - Configuration properties for the component. ### Request Example ```json { "name": "my-user-federation-provider", "providerId": "ldap", "providerType": "org.keycloak.storage.UserStorageProvider", "config": { "priority": "1", "usersDn": "dc=example,dc=com" } } ``` ### Response #### Success Response (200) No content is typically returned on success. #### Response Example ```json null ``` ## GET /{realm}/components ### Description List all components in a realm. ### Method GET ### Endpoint `/{realm}/components` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. #### Query Parameters - **type** (string) - Optional - Filter components by provider type. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **components** (array of objects) - A list of component configurations. #### Response Example ```json [ { "id": "string", "name": "my-user-federation-provider", "providerId": "ldap", "providerType": "org.keycloak.storage.UserStorageProvider", "config": { "priority": "1", "usersDn": "dc=example,dc=com" } } ] ``` ## GET /{realm}/components/{id} ### Description Get a specific component by its ID. ### Method GET ### Endpoint `/{realm}/components/{id}` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The component ID. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **component** (object) - The component configuration. #### Response Example ```json { "id": "string", "name": "my-user-federation-provider", "providerId": "ldap", "providerType": "org.keycloak.storage.UserStorageProvider", "config": { "priority": "1", "usersDn": "dc=example,dc=com" } } ``` ## PUT /{realm}/components/{id} ### Description Update an existing component. ### Method PUT ### Endpoint ``` -------------------------------- ### Components Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=dependencies Manage Keycloak components, which are supported for user federation. This includes creating, listing, retrieving, updating, and deleting components. ```APIDOC ## POST /{realm}/components ### Description Create a new component. ### Method POST ### Endpoint `/{realm}/components` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. #### Request Body - **component** (object) - Required - The configuration of the component to create. ### Request Example ```json { "name": "my-federation-provider", "providerType": "org.keycloak.storage.UserStorageProvider", "providerId": "ldap", "config": { "priority": ["0"], "usernameLDAPAttribute": ["cn"] } } ``` ### Response #### Success Response (200) No content is returned on success. ## GET /{realm}/components ### Description List all components in a realm. ### Method GET ### Endpoint `/{realm}/components` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. #### Query Parameters - **type** (string) - Optional - Filter components by provider type. - **parentId** (string) - Optional - Filter components by parent ID. ### Response #### Success Response (200) - **components** (array) - An array of component objects. ### Response Example ```json [ { "id": "component-id", "name": "my-federation-provider", "providerType": "org.keycloak.storage.UserStorageProvider", "providerId": "ldap" } ] ``` ## GET /{realm}/components/{id} ### Description Get a specific component by its ID. ### Method GET ### Endpoint `/{realm}/components/{id}` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The component ID. ### Response #### Success Response (200) - **component** (object) - The component object. ### Response Example ```json { "id": "component-id", "name": "my-federation-provider", "providerType": "org.keycloak.storage.UserStorageProvider", "providerId": "ldap", "config": { "priority": ["0"], "usernameLDAPAttribute": ["cn"] } } ``` ## PUT /{realm}/components/{id} ### Description Update an existing component. ### Method PUT ### Endpoint `/{realm}/components/{id}` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The component ID. #### Request Body - **component** (object) - Required - The updated configuration of the component. ### Request Example ```json { "name": "updated-federation-provider", "config": { "priority": ["1"] } } ``` ### Response #### Success Response (200) No content is returned on success. ## DELETE /{realm}/components/{id} ### Description Delete a specific component by its ID. ### Method DELETE ### Endpoint `/{realm}/components/{id}` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **id** (string) - Required - The component ID. ### Response #### Success Response (200) No content is returned on success. ``` -------------------------------- ### Keycloak Admin Client: Update User and Reset Password (JavaScript) Source: https://context7.com/context7/npmjs_package_keycloak_keycloak-admin-client/llms.txt Provides code examples for updating existing user details, resetting user passwords (temporary and permanent), sending verification emails, and removing TOTP configurations using the Keycloak Admin Client. Assumes prior authentication and a valid user ID. ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; const kcAdminClient = new KcAdminClient(); await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli' }); const userId = 'a3f8b927-4c5d-4e9a-b8f3-7d2e1c9a8b7c'; try { // Update user information await kcAdminClient.users.update( { id: userId }, { firstName: 'John', lastName: 'Smith', email: 'john.smith@example.com', attributes: { department: ['Sales'], phone: ['555-5678'] } } ); // Set temporary password (user must change on next login) await kcAdminClient.users.resetPassword({ id: userId, credential: { temporary: true, type: 'password', value: 'NewTemporaryPass123!' } }); // Set permanent password await kcAdminClient.users.resetPassword({ id: userId, credential: { temporary: false, type: 'password', value: 'PermanentPass456!' } }); // Send verification email await kcAdminClient.users.sendVerifyEmail({ id: userId, clientId: 'account', redirectUri: 'https://example.com/verified' }); // Remove TOTP await kcAdminClient.users.removeTotp({ id: userId }); console.log('User updated successfully'); } catch (error) { console.error('User update failed:', error.message); } ``` -------------------------------- ### Build Keycloak Admin Client Source Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=dependents Command to build the source code of the Keycloak Admin Client package. ```bash pnpm build ``` -------------------------------- ### Assign Realm Roles to Users with Keycloak Admin Client Source: https://context7.com/context7/npmjs_package_keycloak_keycloak-admin-client/llms.txt This snippet illustrates how to assign realm roles to a specific user, retrieve a user's assigned realm roles, list available roles for a user, get effective roles (including composite roles), and remove realm roles from a user using the keycloak-admin-client. It requires a valid user ID and predefined roles. ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; const kcAdminClient = new KcAdminClient(); await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli' }); const userId = 'a3f8b927-4c5d-4e9a-b8f3-7d2e1c9a8b7c'; try { // Get roles to assign const adminRole = await kcAdminClient.roles.findOneByName({ name: 'admin' }); const managerRole = await kcAdminClient.roles.findOneByName({ name: 'manager' }); // Add realm roles to user await kcAdminClient.users.addRealmRoleMappings({ id: userId, roles: [ { id: adminRole.id, name: adminRole.name }, { id: managerRole.id, name: managerRole.name } ] }); // Get user's realm role mappings const userRoles = await kcAdminClient.users.listRealmRoleMappings({ id: userId }); console.log('User realm roles:', userRoles.map(r => r.name)); // Get available roles for user const availableRoles = await kcAdminClient.users.listAvailableRealmRoleMappings({ id: userId }); // Get effective roles (including composite) const effectiveRoles = await kcAdminClient.users.listCompositeRealmRoleMappings({ id: userId }); // Remove realm roles from user await kcAdminClient.users.delRealmRoleMappings({ id: userId, roles: [{ id: managerRole.id, name: managerRole.name }] }); } catch (error) { console.error('Role mapping failed:', error.message); } ``` -------------------------------- ### Keycloak Admin Client Usage with Password Grant Source: https://www.npmjs.com/package/@keycloak/keycloak-admin-client/package/%40keycloak/keycloak-admin-client_activetab=readme Demonstrates initializing and authorizing the Keycloak Admin Client using username and password credentials. It shows how to list users and find them by attributes, along with reconfiguring the client for different realms and creating users in specific realms. ```javascript import KcAdminClient from '@keycloak/keycloak-admin-client'; // 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(); // Authorize with username / password await kcAdminClient.auth({ username: 'admin', password: 'admin', grantType: 'password', clientId: 'admin-cli', totp: '123456', // optional Time-based One-time Password if OTP is required in authentication flow }); // List first page of users const users = await kcAdminClient.users.find({ first: 0, max: 10 }); // find users by attributes const users = await kcAdminClient.users.find({ q: "phone:123" }); // Override client configuration for all further requests: cnc const groups = await kcAdminClient.groups.find(); // Set a `realm` property to override the realm for only a single operation. // For example, creating a user in another realm: await kcAdminClient.users.create({ realm: 'a-third-realm', username: 'username', email: 'user@example.com', }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.