UNPKG

keycloak-api-manager

Version:

Keycloak-api-manager is a lightweight Node.js wrapper for the Keycloak Admin REST API. It provides an easy-to-use functional methods and functions to manage realms, users, roles, clients, groups, and permissions directly from your application code — just

1,214 lines (1,029 loc) 260 kB
# 🔐 Keycloak Adapter API for Node.js (Express) Keycloak-api-manager is a comprehensive **Node.js library** that wraps the official Keycloak Admin REST API, providing a clean and consistent functional interface for programmatic management of Keycloak resources. With this package, you can easily interact with Keycloak just like through its Admin Console — creating and managing realms, clients, users, roles, groups, permissions, and authentication policies — all via simple JavaScript functions. The library simplifies integration of Keycloak into custom applications, automation scripts, and backend services by handling authentication, API calls, and error management internally. Designed for developers who want full control over Keycloak’s administrative capabilities without manually invoking REST endpoints, keycloak-api-manager enables fast, reliable, and type-safe operations across multiple realms and environments. it is a wrapper based on '@keycloak/keycloak-admin-client' --- ## 📦 Features 🔐 ***Full Keycloak API Coverage*** - Complete wrapper for Keycloak Admin REST API - Manage realms, clients, users, roles, groups, and permissions - Support for both public and confidential clients - Built-in token acquisition and refresh using admin credentials. For the refresh token, it is necessary to correctly set the tokenLifeSpan parameter during configuration ⚙️ ***Administration & Automation*** - Create, update, and delete users, clients, and roles programmatically - Assign and revoke realm and client roles - Manage user credentials, including password resets and temporary logins - Automate realm and client configuration in CI/CD pipelines - Support for bulk operations (e.g., multiple user imports/updates) 🧩 ***Functional and Developer-Friendly API*** - Simple function-based interface instead of raw REST calls - Consistent, predictable naming (e.g., createUser(), assignRole(), getClients()) - Promise-based async functions with proper error handling - Works seamlessly with TypeScript (type definitions included) 🛡️ ***Security & Authentication*** - Built-in admin login flow (client credentials or username/password) - Automatic token refresh and reuse - -Supports custom Keycloak base URLs, ports, and SSL setups - -Optional logging and debug mode for request tracing 🌍 ***Integration & Extensibility*** - Easy integration into Express.js, NestJS, or custom Node.js services - Works with multiple Keycloak instances or environments - Configurable HTTP client, allowing custom interceptors or headers - Can be used as a standalone CLI helper or within applications 🧠 ***Developer Experience*** - Lightweight, dependency-minimal package - Intuitive method structure mirroring Keycloak’s admin console - Clear error messages and optional verbose logging - Fully documented with code examples and usage guides --- ## 🚀 Installation ```bash npm install keycloak-api-manager ``` Or, if using Yarn: ```bash yarn add keycloak-api-manager ``` --- ## 🛠️ Get Keycloak Configuration Copy or Download from keycloak admin page your client configuration `keycloak.json` by visiting the Keycloak Admin Console → clients (left sidebar) → choose your client → Installation → Format Option → Keycloak OIDC JSON → Download ```json { "realm": "your-realm", "auth-server-url": "https://your-keycloak-domain/auth", "ssl-required": "external", "resource": "your-client-id", "credentials": { "secret": "your-client-secret" }, "confidential-port": 0 } ``` --- ## 📄 Usage Example ```js const KeycloakManager = require('keycloak-api-manager'); const express = require('express'); // Import the Keycloak API Manager // Configure and Initialize Keycloak manager api // Initialize the manager with Keycloak credentials await KeycloakManager.configure({ baseUrl: 'http://localhost:8080', // Keycloak base URL realm: 'master', // Realm where the admin user belongs clientId: 'admin-cli', // Keycloak admin client username: 'admin', // Admin username password: 'admin', // Admin password grantType: 'password', // Type of authentication tokenLifeSpan: 120 // access_token Lifetime in seconds }); // Create a new user in the target realm const newUser = await KeycloakManager.users.create({ username: 'john.doe', email: 'john.doe@example.com', firstName: 'John', lastName: 'Doe', enabled: true, }); // List first page of users const users = await KeycloakManager.users.find({ first: 0, max: 10 }); // find users by attributes users = await KeycloakManager.users.find({ q: "phone:123" }); // Override client configuration for all further requests: KeycloakManager.setConfig({ realmName: 'another-realm', }); // This operation will now be performed in 'another-realm' if the user has access. const groups = await KeycloakManager.groups.find(); // Set a `realm` property to override the realm for only a single operation. // For example, creating a user in another realm: await KeycloakManager.users.create({ realm: 'a-third-realm', username: 'username', email: 'user@third-realm.com', }); // create a new realm, If id omitted, Keycloak uses the realm name as the ID. const realm = await KeycloakManager.realms.create({ id: "123456", realm: "new-realm", }); // Get realm Info realm = await KeycloakManager.realms.findOne({ realm: "new-realm" }); console.log("realm info:", realm); ``` --- ## 🧩 Configuration In your Express application: ```js const KeycloakManager = require('keycloak-api-manager'); // Configure and Initialize Keycloak manager api // Initialize the manager with Keycloak credentials await KeycloakManager.configure({ baseUrl: 'http://localhost:8080', // Keycloak base URL realm: 'master', // Realm where the admin user belongs clientId: 'admin-cli', // Keycloak admin client username: 'admin', // Admin username password: 'admin', // Admin password grantType: 'password', // Type of authentication tokenLifeSpan: 120 // access_token Lifetime in seconds }); ``` Configure is a configuration function for the Keycloak-api-manager. It must be called at app startup, before to use the administrative functions exposed by this library Parameters: - adminClientCredentials: [required] Advanced configuration for setting up the realm-admin user or client, which will be used as the administrator to manage Keycloak via API. This is required in order to use the administrative functions exposed by this library. If this parameter is not provided, it will not be possible to use the administrative functions of Keycloak exposed by this adapter, so any attempt to call KeycloakManager.{function} will result in a runtime error due to access on an undefined object Main supported options: - baseUrl: [required] Keycloak base Url - realmName: [required] A String that specifies the realm to authenticate against, if different from the "keyCloakConfig.realm" parameter. If you intend to use Keycloak administrator credentials, this should be set to 'master'. - grantType: [required] The OAuth2 grant type used for authentication. example "password". Possible values: 'password', 'client_credentials', 'refresh_token', etc. - clientId: [required] string containing the client ID configured in Keycloak. Required for all grant types. - tokenLifeSpan: [required] Numeric Lifetime of an access token expressed in seconds. It indicates how often the access token should be renewed. If set incorrectly and the Keycloak token expires before the renewal interval defined by this parameter, errors and exceptions may occur - username: [optional] string username. Required when using the password grant type. - password: [optional] string password. Required when using the password grant type. - scope: [Optional] A string that specifies The OAuth2 scope requested during authentication (optional). Typically, not required for administrative clients. example:openid profile - requestOptions: [Optional] JSON parameters to configure HTTP requests (such as custom headers, timeouts, etc.). It is compatible with the Fetch API standard. Fetch request options https://developer.mozilla.org/en-US/docs/Web/API/fetch#options - clientSecret: [Optional] string containing the client secret of the client. Required for client_credentials or confidential clients. - totp: string for Time-based One-Time Password (TOTP) for multifactor authentication (MFA), if enabled for the user. - offlineToken: [Optional] boolean value. If true, requests an offline token (used for long-lived refresh tokens). Default is false. - refreshToken: [Optional] string containing a valid refresh token to request a new access token when using the refresh_token grant type. --- ## 🔧 Available Admin Functions All administrative functions that rely on Keycloak's Admin API must be invoked using the KeycloakManager.{entity}.{function} pattern. - {entyty} represents the type of resource you want to manage (e.g., users, roles, groups, clients). - {function} is the specific operation you want to perform on that resource (e.g., find, create, update, del). For example: ```js const KeycloakManager = require('keycloak-api-manager'); // get all users of this client // users is the entity you want to administer. // find is the method used to retrieve the list of users. KeycloakManager.users.find(); ``` Credits to @keycloak/keycloak-admin-client. This admin function is built on top of it. For more details, please refer to the official repository. ### `entity realm` The realms property provides access to all administrative operations related to Keycloak realms. A realm in Keycloak is a fundamental concept that acts as an isolated tenant: each realm manages its own set of users, roles, groups, and clients independently. #### `entity realm functions` ##### `function create(realm-dictionary)` create is a method used to create a new realm. This method accepts a realm representation object containing details such as is, name **` -- @parameters -- `** - realm-dictionary: is a JSON object that accepts filter parameters - id:[required] The internal ID of the realm. If omitted, Keycloak uses the realm name as the ID. - realm:[required] The name of the realm to create. - { other fields }Additional optional properties can be passed to configure the realm (e.g., enabled, displayName, etc.). ```js const KeycloakManager = require('keycloak-api-manager'); // create a new realm const realm = await KeycloakManager.realms.create({ id: "realm-id", realm: "realmName", }); ``` ##### `function update(filter,realm-dictionary)` Updates the configuration of an existing realm. You can use this method to modify settings such as login behavior, themes, token lifespans, and more. **` -- @parameters -- `** - filter:is a JSON object that accepts filter parameters - realm:[required] The identifier of the realm you want to update. - realm-dictionary: An object containing the updated realm configuration. Only the fields you want to change need to be included. - realm properties that can be passed to update the realm (e.g., enabled, displayName, etc.). ```js const KeycloakManager = require('keycloak-api-manager'); // update a realm await KeycloakManager.realms.update( { realm: 'realm-name' }, { displayName: "test", } ); ``` ##### `function del(filter)` Deletes a specific realm from the Keycloak server. This operation is irreversible and removes all users, clients, roles, groups, and settings associated with the realm. **` -- @parameters -- `** - filter: is a JSON object that accepts filter parameters - realm:[required] The name of the realm to delete. ```js const KeycloakManager = require('keycloak-api-manager'); // delete 'realmeName' realm const realm = await KeycloakManager.realms.del({ realm: "realmName", }); ``` ##### `function find()` Retrieves a list of all realms configured in the Keycloak server. This includes basic metadata for each realm such as ID and display name, but not the full configuration details. This method does not take any parameters. ```js const KeycloakManager = require('keycloak-api-manager'); // delete 'realmeName' realm const realms = await KeycloakManager.realms.find(); console.log("Retrieved realms:",realms); ``` ##### `function findOne(filter)` Retrieves the full configuration and metadata of a specific realm by its name (realm ID). This includes settings like login policies, themes, password policies, etc. **` -- @parameters -- `** - filter: is a JSON object that accepts filter parameters - realm:[required] The name (ID) of the realm you want to retrieve. ```js const KeycloakManager = require('keycloak-api-manager'); // delete 'realmeName' realm const realmConfig = await KeycloakManager.realms.findOne({ realm: "realmName", }); console.log("Retrieved realm:",realmConfig); ``` ##### `function partialImport(configuration)` Performs a partial import of realm configuration into a Keycloak realm. This allows you to import users, roles, groups, clients, and other components without replacing the entire realm. It’s useful for incremental updates or merging configuration pieces. **` -- @parameters -- `** - configuration: is a JSON object that accepts filter parameters - realm:[required] The name of the realm where the data should be imported. - representation:[required] A JSON object representing part of the realm configuration to be imported(can include users, roles, groups, clients, etc.). - ifResourceExists:[required] Defines the behavior when an imported resource already exists in the target realm. Options are: - 'FAIL' – the operation fails if a resource already exists. - 'SKIP' – existing resources are skipped. - 'OVERWRITE' – existing resources are overwritten. - {other fields} other configuration to be imported like users, roles, groups ... ```js const KeycloakManager = require('keycloak-api-manager'); // import configuration const roleToImport: PartialImportRealmRepresentation = { ifResourceExists: "FAIL", roles: { realm: [ { id: "9d2638c8-4c62-4c42-90ea-5f3c836d0cc8", name: "myRole", scopeParamRequired: false, composite: false, }, ], }, }; // partial realm import const result = await KeycloakManager.realms.partialImport({ realm: 'my-realm', rep: roleToImport, }); ``` ##### `function export(configuration)` Exports the configuration of a specific realm. This method returns the full realm representation in JSON format, including roles, users, clients, groups, and other components depending on the provided options. **` -- @parameters -- `** - configuration: is a JSON object that accepts filter parameters - realm:[required] The name of the realm to export. - exportClients: [optional] boolean, Whether to include clients in the export. Default: true. - exportGroupsAndRoles: [optional] boolean, Whether to include groups and roles in the export. Default: true. ```js const KeycloakManager = require('keycloak-api-manager'); // realm export const exportedRealm = await KeycloakManager.realms.export({ realm: 'my-realm', exportClients: true, // optional exportGroupsAndRoles: true, // optional }); // print exportedRealm console.log(JSON.stringify(exportedRealm, null, 2)); ``` ##### `function getClientRegistrationPolicyProviders(configuration)` Fetches the list of available client registration policy providers for the specified realm. These providers define how new clients can be registered and what rules or validations apply (e.g., allowed scopes, required attributes). **` -- @parameters -- `** - configuration: is a JSON object that accepts filter parameters - realm:[required] The name of the realm where you want to list client registration policy providers. ```js const KeycloakManager = require('keycloak-api-manager'); // get Client Registration Policy Providers await KeycloakManager.realms.getClientRegistrationPolicyProviders({ realm: currentRealmName, }); ``` ##### `function createClientsInitialAccess(realmFilter,options)` Creates a new Initial Access Token for dynamic client registration. This token allows clients to register themselves with the realm using the Dynamic Client Registration API. Useful when you want to allow programmatic client creation in a controlled way. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm:[required] The name of the realm where the initial access token should be created. - options: is a JSON object that accepts filter parameters - count [required] Number of times this token can be used to register new clients. - expiration [required] Time (in seconds) after which the token expires. 0 is unlimited @return - Returns an object containing: - id: internal ID of the token - token: the actual token string to be used during dynamic registration - timestamp: Creation timestamp - expiration: Expiration time in seconds - count: Maximum allowed uses - remainingCount: How many uses are left ```js const KeycloakManager = require('keycloak-api-manager'); // get Client Registration Policy Providers with oount=1 and unlimited expiration time const initialAccess= await KeycloakManager.realms.realms.createClientsInitialAccess( { realm: currentRealmName }, { count: 1, expiration: 0 }, ); console.log("Initial Access Token:", initialAccess.token); ``` ##### `function getClientsInitialAccess(realmFilter)` Retrieves all existing Initial Access Tokens for dynamic client registration in a given realm. These tokens are used to allow programmatic or automated registration of clients via the Dynamic Client Registration API. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm:[required] The name of the realm from which to list all initial access tokens. @return - An array of objects representing each initial access token. Each object contains: - id: internal ID of the token - token: the actual token string to be used during dynamic registration - timestamp: Creation timestamp - expiration: Expiration time in seconds - count: Maximum allowed uses - remainingCount: How many uses are left ```js const KeycloakManager = require('keycloak-api-manager'); // get get Clients Initial Access list const tokens= await KeycloakManager.realms.getClientsInitialAccess({ realm:'realm-id'}); console.log("Initial Access Tokens:", tokens); ``` ##### `function delClientsInitialAccess(realmFilter)` Deletes a specific Initial Access Token used for dynamic client registration in a given realm. This revokes the token, preventing any future use. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm:[required] The name of the realm where the token was created. - id:[required] The ID of the initial access token you want to delete. ```js const KeycloakManager = require('keycloak-api-manager'); // delete Clients Initial Access await KeycloakManager.realms.delClientsInitialAccess({ realm: 'realm-id', id: 'initial-access-token-id', }); ``` ##### `function addDefaultGroup(realmFilter)` Adds an existing group to the list of default groups for a given realm. Users created in this realm will automatically be added to all default groups. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm:[required] The name of the realm where the default group will be set. - id:[required] The ID of the group to be added as a default group ```js const KeycloakManager = require('keycloak-api-manager'); // get get Clients Initial Access list await KeycloakManager.realms.addDefaultGroup({ realm: 'realm-id', id: 'default-group-id', }); ``` ##### `function removeDefaultGroup(realmFilter)` Removes a group from the list of default groups in a realm. Default groups are automatically assigned to new users when they are created. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm:[required] The name of the realm from which to remove the default group. - id:[required] The ID of the group you want to remove from the default list. ```js const KeycloakManager = require('keycloak-api-manager'); // remove from 'realm-id' the group 'default-group-id' await KeycloakManager.realms.removeDefaultGroup({ realm: 'realm-id', id: 'default-group-id', }); ``` ##### `function getDefaultGroups(realmFilter)` Retrieves a list of all default groups for a specified realm. These are the groups that new users will automatically be added to upon creation. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm:[required] The name of the realm from which to retrieve default groups. ```js const KeycloakManager = require('keycloak-api-manager'); // get 'realm-id' default groups const defaultGroups = await KeycloakManager.realms.getDefaultGroups({ realm: 'realm-id', }); console.log(defaultGroups); ``` ##### `function getGroupByPath(realmFilter)` Retrieves a group object by specifying its hierarchical path in a realm. This is useful when you know the group’s full path (e.g., /parent/child) but not its ID. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm:[required] The name of the realm where the group is located. - path:[required] TThe full hierarchical path to the group, starting with a slash (/). For example: /developers/frontend. ```js const KeycloakManager = require('keycloak-api-manager'); // get 'realm-id' group by Path const defaultGroups = await KeycloakManager.realms.getGroupByPath({ realm: 'realm-id', path: 'realm-name-path' }); console.log(defaultGroups); ``` ##### `function getConfigEvents(realmFilter)` Retrieves the event configuration settings for a specific realm. This includes settings related to the event listeners, enabled event types, admin events, and more. Useful for auditing and tracking activities inside Keycloak. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm:[required] The name of the realm from which to retrieve the event configuration. ```js const KeycloakManager = require('keycloak-api-manager'); // get Config Events const config= await KeycloakManager.realms.getConfigEvents({ realm: 'realm-id', }); console.log(config); /* config example: { eventsEnabled: true, eventsListeners: ['jboss-logging'], enabledEventTypes: ['LOGIN', 'LOGOUT', 'REGISTER'], adminEventsEnabled: true, adminEventsDetailsEnabled: false } */ ``` ##### `function updateConfigEvents(realmFilter,configurationEvents)` Updates the event configuration for a given realm. This includes enabling/disabling events, setting specific event types to track, enabling admin event logging, and choosing which event listeners to use. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm:[required] The name of the realm where the configuration will be updated. - configurationEvents:is a config events JSON object dictionary like this: - eventsEnabled: Enables or disables event logging. - eventsListeners: List of event listener IDs to use (e.g., ["jboss-logging"]). - enabledEventTypes: List of event types to track (e.g., ["LOGIN", "LOGOUT", "REGISTER"]). - adminEventsEnabled: Enables logging for admin events. - adminEventsDetailsEnabled: Includes full details in admin event logs if set to true. ```js const KeycloakManager = require('keycloak-api-manager'); // Update Config Events const config= await KeycloakManager.realms.updateConfigEvents( { realm: 'realm-id'}, { eventsEnabled: true, eventsListeners: ['jboss-logging'], enabledEventTypes: ['LOGIN', 'LOGOUT', 'UPDATE_PASSWORD'], adminEventsEnabled: true, adminEventsDetailsEnabled: true, }); ``` ##### `function findEvents(realmFilter)` Retrieves a list of events that occurred in a specified realm. You can filter the results by event type, user, date range, and other criteria. Useful for auditing login, logout, and other user-related activities. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm: [required] The name of the realm to fetch events from. - client: [optional] Client ID to filter events for a specific client. - type: [optional] Event type to filter (e.g., LOGIN, REGISTER). - user: [optional] User ID to filter events related to a specific user. - dateFrom: [optional] Start date in ISO 8601 format to filter events. - dateTo: [optional] End date in ISO 8601 format to filter events. - first: [optional] Pagination offset. - max: [optional] Maximum number of events to return. ```js const KeycloakManager = require('keycloak-api-manager'); // find 10 realm-id events with a type=LOGIN and dateFrom and dateTo. const config= await KeycloakManager.realms.findEvents({ realm: 'realm-id', type: 'LOGIN', dateFrom: '2025-08-01T00:00:00Z', dateTo: '2025-08-06T23:59:59Z', max: 10 }); ``` ##### `function findAdminEvents(realmFilter)` Retrieves administrative events that occurred in a specific realm. Admin events are triggered by actions such as creating users, updating roles, or modifying realm settings. This is useful for auditing changes made via the admin API or admin console. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm: [required] The name of the realm to retrieve admin events from. - authClient: [optional] Client ID used to perform the action. - authIpAddress: [optional] IP address of the actor who triggered the event. - authRealm: [optional] Realm of the actor. - authUser: [optional] User ID of the admin who performed the action. - dateFrom: [optional] Start date in ISO 8601 format. - dateTo: [optional] End date in ISO 8601 format. - first: [optional] Pagination offset. - max: [optional] Maximum number of events to retrieve. - operationTypes: [optional] Filter by operation type (e.g., CREATE, UPDATE, DELETE). - resourcePath: [optional] Filter events by resource path. - resourceTypes: [optional] Filter events by resource type (e.g., USER, REALM_ROLE, CLIENT). ```js const KeycloakManager = require('keycloak-api-manager'); // find 10 realm-id admin events with a type=CREATE|DELETE and dateFrom and dateTo. const config= await KeycloakManager.realms.findAdminEvents({ realm: 'realm-id', operationTypes: ['CREATE', 'DELETE'], dateFrom: '2025-08-01T00:00:00Z', dateTo: '2025-08-06T23:59:59Z', max: 10 }); ``` ##### `function clearEvents(realmFilter)` Deletes all user events (not admin events) from the event store of a specific realm. Useful for resetting or cleaning up event logs related to user actions such as logins, logouts, failed login attempts, etc. This does not clear administrative events. To remove those, use realms.clearAdminEvents(). **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm: [required] The name of the realm from which to clear user events. ```js const KeycloakManager = require('keycloak-api-manager'); // clear realm-id events const config= await KeycloakManager.realms.clearEvents({ realm: 'realm-id', }); ``` ##### `function clearAdminEvents(realmFilter)` Deletes all admin events from the event store of a specific realm. Admin events include actions such as creating users, updating roles, changing client settings, etc., performed by administrators via the Admin Console or Admin REST API. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm: [required] The name of the realm from which to clear administrative events. ```js const KeycloakManager = require('keycloak-api-manager'); // clear realm-id admin events const config= await KeycloakManager.realms.clearAdminEvents({ realm: 'realm-id', }); ``` ##### `function getUsersManagementPermissions(realmFilter)` Retrieves the status and configuration of user management permissions (also known as fine-grained permissions) in a specific realm. This allows you to check whether user management operations (like creating, updating, or deleting users) are protected by specific roles or policies. **` -- @parameters -- `** - realmFilter: is a JSON object that accepts filter parameters - realm: [required] The name of the realm for which you want to retrieve the user management permission settings. Returns an object with information such as: ```js const KeycloakManager = require('keycloak-api-manager'); { enabled: boolean; resource: string; scopePermissions: { } } ``` if enabled is false, user management operations are not restricted by fine-grained permissions. You can enable or configure these permissions using updateUsersManagementPermissions() ```js const KeycloakManager = require('keycloak-api-manager'); // Get Permissions const permissions= await KeycloakManager.realms.getUsersManagementPermissions({ realm: 'realm-id', }); console.log(permissions.enabled); // true or false ``` ##### `function updateUsersManagementPermissions(update-parameters)` Enables or disables fine-grained user management permissions in a specified realm. This controls whether operations on users (such as creating, editing, or deleting users) are protected using Keycloak's authorization services. **` -- @parameters -- `** - update-parameters: is a JSON object that accepts this parameters - realm: [required] The name of the realm for which you want to update the user management permission settings. - enabled: [required] boolean value to enable or disable permission - true: Activates fine-grained permissions for user management. - false: Disables fine-grained permissions and falls back to standard admin roles. Returns an object with information such as: ```js const KeycloakManager = require('keycloak-api-manager'); { enabled: boolean; resource: string; scopePermissions: { } } ``` ```js const KeycloakManager = require('keycloak-api-manager'); // Update Permissions const permissions= await KeycloakManager.realms.updateUsersManagementPermissions({ realm: 'realm-id', }); console.log(permissions.enabled); // true ``` ##### `function getKeys(filter)` Retrieves the realm keys metadata, including public keys, certificates, and active key information used for token signing, encryption, and other cryptographic operations in the specified realm. **` -- @parameters -- `** - filter: is a JSON object that accepts this parameters - realm: [required] The name of the realm for which you want to retrieve key metadata. Returns a list of keys and related information: ``` { keys: [ { kid: string; // Key ID type: string; // Key type (e.g., RSA, AES) providerId: string; // Key provider ID providerPriority: //number; publicKey?: string; // Base64-encoded public key (if applicable) certificate?: string; // X.509 certificate (if available) algorithm: string; // Signing algorithm (e.g., RS256) status: string; // Status (e.g., ACTIVE, PASSIVE) use: string; // Intended use (e.g., sig for signature, enc for encryption) }, ... ] } ``` ```js const KeycloakManager = require('keycloak-api-manager'); // Get Keys const Keys= await KeycloakManager.realms.getKeys({ realm: 'realm-id', }); console.log(Keys); ``` ##### `function getClientSessionStats(filter)` Retrieves statistics about active client sessions in the specified realm. This includes the number of active sessions per client. **` -- @parameters -- `** - filter: is a JSON object that accepts this parameters - realm: [required] The name of the realm for which you want to retrieve client session statistics. Returns an array of objects, each representing a client with active sessions ```js const KeycloakManager = require('keycloak-api-manager'); // Get Client Session Stats const stats= await KeycloakManager.realms.getClientSessionStats({ realm: 'realm-id', }); console.log(stats); /* [ { clientId: 'frontend-app', active: 5 }, { clientId: 'admin-cli', active: 1 }, ... ] */ ``` ##### `function pushRevocation(filter)` Immediately pushes a revocation policy to all clients in the specified realm. This forces clients to revalidate tokens, effectively revoking cached access tokens and enforcing updated policies. **` -- @parameters -- `** - filter: is a JSON object that accepts this parameters - realm: [required] The name of the realm where the revocation should be pushed. ```js const KeycloakManager = require('keycloak-api-manager'); // push revocaiton to realm realm-id const pushR= await KeycloakManager.realms.pushRevocation({ realm: 'realm-id', }); console.log(pushR); ``` ##### `function logoutAll(filter)` Logs out all active sessions for all users in the specified realm. This invalidates all user sessions, forcing every user to re-authenticate. **` -- @parameters -- `** - filter: is a JSON object that accepts this parameters - realm: [required] The name of the realm from which to log out all users. ```js const KeycloakManager = require('keycloak-api-manager'); // force all users logout in realm realm-id const logout= await KeycloakManager.realms.logoutAll({ realm: 'realm-id', }); console.log('logout results:',logout); ``` ##### `function testLDAPConnection(filter,options)` Tests the connection to an LDAP server using the provided configuration parameters. This is useful to verify that Keycloak can reach and authenticate with the LDAP server before fully integrating it into the realm configuration. **` -- @parameters -- `** - filter: is a JSON object that accepts this filter parameters - realm: [required] Name of the realm where the LDAP provider is being tested. - options: is a JSON object that accepts this parameters - action: [required] Specifies the test type. Use "testConnection" to verify the connection, or "testAuthentication" to verify bind credentials. - connectionUrl: [required] URL of the LDAP server (e.g., ldap://ldap.example.com:389). - bindDn: [required] Distinguished Name (DN) used to bind to the LDAP server. - bindCredential: [required] Password or secret associated with the bind DN. - useTruststoreSpi: [optional] Whether to use the truststore ("ldapsOnly", "always", etc.). - connectionTimeout: [optional] Timeout value for the connection (in milliseconds). - authType: [optional] Type of authentication; usually "simple" or "none". ```js const KeycloakManager = require('keycloak-api-manager'); //should fail with invalid ldap settings try { await KeycloakManager.realms.testLDAPConnection( { realm: "realm-name" }, { action: "testConnection", authType: "simple", bindCredential: "1", bindDn: "1", connectionTimeout: "", connectionUrl: "1", startTls: "", useTruststoreSpi: "always", }, ); fail("exception should have been thrown"); } catch (error) { console.log(error); // exception should have been thrown } ``` ##### `function ldapServerCapabilities(filter,options)` This function queries the LDAP server configured for a specific realm to retrieve and display its supported capabilities. It helps validate the connection and understand which LDAP features are available, such as supported controls, extensions, authentication mechanisms, and more. **` -- @parameters -- `** - filter: is a JSON object that accepts this filter parameters - realm: [required] Name of the realm where the LDAP provider is being tested. - options: is a JSON object that accepts this parameters - action: [required] Specifies the test type. Use "testConnection" to verify the connection, or "testAuthentication" to verify bind credentials. - connectionUrl: [required] URL of the LDAP server (e.g., ldap://ldap.example.com:389). - bindDn: [required] Distinguished Name (DN) used to bind to the LDAP server. - bindCredential: [required] Password or secret associated with the bind DN. - useTruststoreSpi: [optional] Whether to use the truststore ("ldapsOnly", "always", etc.). - connectionTimeout: [optional] Timeout value for the connection (in milliseconds). - authType: [optional] Type of authentication; usually "simple" or "none". ```js const KeycloakManager = require('keycloak-api-manager'); // should fail with invalid ldap server capabilities try { await KeycloakManager.realms.ldapServerCapabilities( { realm: "realm-name" }, { action: "testConnection", authType: "simple", bindCredential: "1", bindDn: "1", connectionTimeout: "", connectionUrl: "1", startTls: "", useTruststoreSpi: "always", }, ); fail("exception should have been thrown"); } catch (error) { console.log(error); // exception should have been thrown } ``` ##### `function testSMTPConnection(filter,config)` Tests the SMTP connection using the provided configuration. This allows you to verify that Keycloak can connect and send emails through the configured SMTP server before applying the settings to the realm. **` -- @parameters -- `** - filter: is a JSON object that accepts this filter parameters - realm: [required] The name of the realm where the SMTP server will be tested. - config: An object containing the SMTP server configuration: - from: [required] The sender email address. - host: [required] The SMTP server host (e.g., smtp.example.com). - port: [required] The SMTP server port (usually 587, 465, or 25). - auth: [optional] Whether authentication is required ("true" or "false"). - user [optional] The username for SMTP authentication. - password [optional] The password for SMTP authentication. - replyTo [optional] The reply-to email address. - starttls [optional] Enable STARTTLS ("true" or "false"). - ssl [optional] Enable SSL ("true" or "false"). - envelopeFrom [optional] Envelope sender address. ```js const KeycloakManager = require('keycloak-api-manager'); // should fail with invalid smtp settings try { await KeycloakManager.realms.testSMTPConnection( { realm: "master" }, { from: "test@test.com", host: "localhost", port: 3025, }, ); fail("exception should have been thrown"); } catch (error) { console.log(error); // exception should have been thrown } ``` ##### `function getRealmLocalizationTexts(filter)` Retrieves all localization texts (custom messages and labels) defined for a specific realm and locale. Localization texts are used to override default Keycloak UI messages for login forms, error pages, and other user-facing content **` -- @parameters -- `** - filter: is a JSON object that accepts this filter parameters - realm: [required] The name of the realm from which to fetch localization texts. - selectedLocale: [required] The locale code (e.g., 'en', 'it', 'fr', etc.) for which you want to retrieve the translations. ```js const KeycloakManager = require('keycloak-api-manager'); // Realm localization const texts= await KeycloakManager.realms.getRealmLocalizationTexts({ realm: "realm-id", selectedLocale:'it' }); console.log(texts); ``` ##### `function addLocalization(filter,value)` Adds or updates a localization text (custom UI message or label) for a specific realm and locale in Keycloak. This allows you to override default messages in the login screens and other UI components with custom translations. **` -- @parameters -- `** - filter: is a JSON object that accepts this filter parameters - realm: [required] The name of the realm where the localization should be applied. - selectedLocale: [required] The locale code (e.g., 'en', 'fr', 'it') for which the translation is being added. - key: [required] The message key or identifier to override (e.g., loginAccountTitle, errorInvalidUsername). - value: [required] The actual translated text to associate with the key for the given locale. ```js const KeycloakManager = require('keycloak-api-manager'); // should add localization await KeycloakManager.realms.addLocalization({ realm: "realm-id", selectedLocale:'it', key:"theKey" },"new Value String for key:theKey"); ``` ##### `function getRealmSpecificLocales(filter)` Retrieves the list of locales (language codes) for which custom localization texts have been defined in a specific realm. This function is useful to determine which locales have at least one overridden message. **` -- @parameters -- `** - filter: is a JSON object that accepts this filter parameters - realm: [required] The name of the realm for which to fetch the list of custom locales. - selectedLocale: [optional] The locale code (e.g., 'en', 'fr', 'it'). Return An array of locale codes (e.g., ["en", "it", "fr"]) representing the languages that have at least one customized localization entry in the given realm. ```js const KeycloakManager = require('keycloak-api-manager'); // should add localization await KeycloakManager.realms.addLocalization({ realm: "realm-id", selectedLocale:'it', key:"theKey" },"new Value String for key:theKey"); // should get localization for specified locale const specificLocales= await KeycloakManager.realms.getRealmSpecificLocales({ realm: "realm-id", selectedLocale: "it", }); console.log(specificLocales.thekey); // new Value String for key:theKey ``` ##### `function deleteRealmLocalizationTexts(filter)` Deletes a specific custom localization text entry for a given locale and key within a realm. This is useful when you want to remove a previously added or overridden message from the realm's custom localization. **` -- @parameters -- `** - filter: is a JSON object that accepts this filter parameters - realm: [required] The name of the realm where the localization entry exists. - selectedLocale: [required] The locale code (e.g., 'en', 'fr', 'it'). - key: [optional] The key identifying the message you want to remove. If no key is specified, all keys will be removed Returns void if the deletion is successful. Will throw an error if the entry does not exist or if parameters are invalid. ```js const KeycloakManager = require('keycloak-api-manager'); // should delete localization for specified locale key 'theKey' await KeycloakManager.realms.deleteRealmLocalizationTexts({ realm: "realm-id", selectedLocale: "it", key:'theKey' }); ``` ### `entity users` The roles users refers to Keycloak's users management functionality, part of the Admin REST API. It allows you to create, update, inspect, and delete both realm-level and client-level users. #### `entity roles functions` ##### `function create(userRepresentation)` create is a method used to create a new user in the specified realm. This method accepts a user representation object containing details such as username, email, enabled status, credentials, and other user attributes that can be get by getProfile function. It is typically used when you want to programmatically add new users to your Keycloak realm via the Admin API. **` -- @parameters -- `** - userRepresentation: An object containing the user fields to be updated. ```js const KeycloakManager = require('keycloak-api-manager'); // create a new user const userProfile = await KeycloakManager.users.create({ username:"username", email: "test@keycloak.org", // enabled required to be true in order to send actions email emailVerified: true, enabled: true, attributes: { key: "value", }, }); ``` ##### `function del(filter)` Deletes a user from the specified realm. Once removed, the user and all associated data (such as credentials, sessions, and group/role memberships) are permanently deleted. **` -- @parameters -- `** - id: [Required] the user ID to delete - realm [Optional] the realm name (defaults to current realm) ```js const KeycloakManager = require('keycloak-api-manager'); // delete a user const userProfile = await KeycloakManager.users.del({ id: 'user-Id' }); ``` ##### `function find(filter)` find method is used to retrieve a list of users in a specific realm. It supports optional filtering parameters such as username, email, first name, last name, and more. Searching by attributes is only available from Keycloak > 15 **` -- @parameters -- `** - filter: parameter provided as a JSON object that accepts the following filter: - q: A string containing a query filter by custom attributes, such as 'username:admin'. - {builtin attribute}: To find users by builtin attributes such as email, surname... example {email:"admin@admin.com"} - max: A pagination parameter used to define the maximum number of users to return (limit). - first: A pagination parameter used to define the number of users to skip before starting to return results (offset/limit). ```js const KeycloakManager = require('keycloak-api-manager'); // find a user with 'key:value' const user = await KeycloakManager.users.find({ q: "key:value" });; if(user) console.log('User found:', user); else console.log('User not found'); // find a user by name = John user = await KeycloakManager.users.find({ name: "John" });; if(user) console.log('User found:', user); else console.log('User not found'); // find a user with 'name:john', skip 10 users and limt to 5 const user = await KeycloakManager.users.find({ q: "name:john", first:11, max:5});; if(user) console.log('User found:', user); else console.log('User not found'); ``` ##### `function findOne(filter)` findOne is method used to retrieve a specific user's details by their unique identifier (id) within a given realm. It returns the full user representation if the user exists. ```js const KeycloakManager = require('keycloak-api-manager'); // find a user with id:'user-id' const user = await KeycloakManager.users.findOne({ id: 'user-id' }); if(user) console.log('User found:', user); else console.log('User not found'); ``` ##### `function count(filter)` count method returns the total number of users in a given realm. It optionally accepts filtering parameters similar to those in users.find() such as username, email, firstName, lastName and so on to count only users that match specific criteria. Searching by attributes is only available from Keycloak > 15 **` -- @parameters -- `** - filter is a JSON object that accepts filter parameters, such as { email: 'test@keycloak.org' } ```js const KeycloakManager = require('keycloak-api-manager'); // Return the total number of registered users const user_count = await KeycloakManager.users.count(); console.log('User found:', user_count); // Return the number of users with the name "John" user_count = await KeycloakManager.users.count({name:'Jhon'}); console.log('User found:', user_count); ``` ##### `function update(searchParams,userRepresentation)` update method is used to update the details of a specific user in a Keycloak realm. It requires at least the user’s ID(searchParams) and the updated data(userRepresentation). You can modify fields like firstName, lastName, email, enabled, and more. **` -- @parameters -- `** - searchParams: is a JSON object that accepts filter parameters - id: [Required] the user ID to update - realm [Optional] the realm name (defaults to current realm) - userRepresentation: An object containing the user fields to be updated. ```js const KeycloakManager = require('keycloak-api-manager'); // Update user with id:'user-id' const user_count = await KeycloakManager.users.update({ id: 'user-Id' }, { firstName: 'John', lastName: 'Updated', enabled: true, }); ``` ##### `function resetPassword(newCredentialsParameters)` resetPassword method is used to set a new password for a specific user. This action replaces the user's existing credentials. You can also set whether the user is required to change the password on next login. **` -- @parameters -- `** - newCredentialsParameters: is a JSON object that accepts filter parameters - id: [Required] the user ID to update - realm [Optional] the realm name (defaults to current realm) - credential: An object containing the new user credentials - temporary: true or false. Whether the new password is temporary (forces user to reset at next login). - type: a String value set to "password" - value: a String containing new password to be set ```js const KeycloakManager = require('keycloak-api-manager'); // Update user with id:'user-id' const user = await KeycloakManager.users.resetPassword({ id: userId, credential:{ temporary: false, type: "password", value: "test" } }); ``` ##### `function getCredentials(filter)` getCredentials() method retrieves the list of credentials (e.g., passwords, OTPs,