keycloak-api-manager 3.1.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.mocharc.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "require": ["test/mocha.env.js"],
3
+ "timeout": 15000,
4
+ "spec": "test/**/*.test.js",
5
+ "reporter": "spec",
6
+ "parallel": false
7
+ }
@@ -218,7 +218,7 @@ exports.updateRequiredAction=function(filter,actionRepresentation){
218
218
  * @parameters:
219
219
  * - filter: parameter provided as a JSON object that accepts the following filter:
220
220
  * - alias: [required] The alias (providerId) of the required action to update.
221
- * - actionRepresentation: The configuration object to update.
221
+ * - actionConfigRepresentation: The configuration object to update.
222
222
  */
223
223
  exports.updateRequiredActionConfig=function(filter, actionConfigRepresentation){
224
224
  return (kcAdminClientHandler.authenticationManagement.updateRequiredActionConfig(filter,actionConfigRepresentation));
@@ -20,8 +20,8 @@ exports.setKcAdminClient=function(kcAdminClient){
20
20
  * A client scope defines a set of protocol mappers and roles that can be applied to clients,
21
21
  * such as during login or token generation.
22
22
  */
23
- exports.create=function(scopeRappresentation){
24
- return (kcAdminClientHandler.clientScopes.create(scopeRappresentation ));
23
+ exports.create=function(scopeRepresentation){
24
+ return (kcAdminClientHandler.clientScopes.create(scopeRepresentation ));
25
25
  }
26
26
 
27
27
 
@@ -35,13 +35,13 @@ exports.create=function(scopeRappresentation){
35
35
  * - filter: parameter provided as a JSON object that accepts the following filter:
36
36
  * - id: [required] The unique ID of the client scope to update.
37
37
  * - realm: [optional] The realm where the client scope exists.
38
- * - scopeRappresentation: The updated client scope object.
38
+ * - scopeRepresentation: The updated client scope object.
39
39
  * - name: [optional] The name of the scope
40
40
  * - description: [optional] The scope description
41
41
  * - {other scope fields}
42
42
  */
43
- exports.update=function(filter,scopeRappresentation){
44
- return (kcAdminClientHandler.clientScopes.update(filter,scopeRappresentation ));
43
+ exports.update=function(filter,scopeRepresentation){
44
+ return (kcAdminClientHandler.clientScopes.update(filter,scopeRepresentation ));
45
45
  }
46
46
 
47
47
 
@@ -195,7 +195,7 @@ exports.getClientSecret=function(filter){
195
195
  * - id: [required] The internal ID of the client (not clientId)
196
196
  */
197
197
  exports.generateNewClientSecret=function(filter){
198
- return (kcAdminClientHandler.clients.creatgenerateNewClientSecrete(filter));
198
+ return (kcAdminClientHandler.clients.generateNewClientSecret(filter));
199
199
  }
200
200
 
201
201
 
@@ -60,8 +60,8 @@ exports.create=function(componentRepresentation){
60
60
  * - bindCredential: ["secret"],
61
61
  * - usersDn: ["ou=users,dc=example,dc=com"]
62
62
  */
63
- exports.update=function(filters, componentRepresentation){
64
- return (kcAdminClientHandler.components.update(filters, componentRepresentation));
63
+ exports.update=function(filter, componentRepresentation){
64
+ return (kcAdminClientHandler.components.update(filter, componentRepresentation));
65
65
  }
66
66
 
67
67
 
@@ -25,8 +25,8 @@ exports.setKcAdminClient=function(kcAdminClient){
25
25
  * - description: [optional] the new group Description
26
26
  * - {other [optional] group description fields}
27
27
  */
28
- exports.create=function(groupRappresentation){
29
- return (kcAdminClientHandler.groups.create(groupRappresentation));
28
+ exports.create=function(groupRepresentation){
29
+ return (kcAdminClientHandler.groups.create(groupRepresentation));
30
30
  }
31
31
 
32
32
 
@@ -18,7 +18,7 @@ exports.setKcAdminClient=function(kcAdminClient){
18
18
  * or another SAML/OIDC provider.
19
19
  * This method requires specifying an alias, the provider type, and configuration settings such as client ID, client secret, and any other provider-specific options.
20
20
  * @parameters:
21
- * - identityProvidersRappresentation: parameter provided as a JSON object containing the configuration of the Identity Provider
21
+ * - identityProvidersRepresentation: parameter provided as a JSON object containing the configuration of the Identity Provider
22
22
  * - alias: [required] Unique name for the IdP within the realm.
23
23
  * - providerId: [required] Type of provider (google, facebook, oidc, saml, etc.).
24
24
  * - enabled: [optional] Whether the IdP is enabled. Default is true.
@@ -29,8 +29,8 @@ exports.setKcAdminClient=function(kcAdminClient){
29
29
  * - firstBrokerLoginFlowAlias: [optional] Flow to use on first login.
30
30
  * - config : [optional] Provider-specific configuration, e.g., client ID, client secret, endpoints, etc.
31
31
  */
32
- exports.create=function(identityProvidersRappresentation){
33
- return (kcAdminClientHandler.identityProviders.create(identityProvidersRappresentation));
32
+ exports.create=function(identityProvidersRepresentation){
33
+ return (kcAdminClientHandler.identityProviders.create(identityProvidersRepresentation));
34
34
  }
35
35
 
36
36
  /**
package/README.md CHANGED
@@ -95,7 +95,7 @@ const express = require('express');
95
95
  // Initialize the manager with Keycloak credentials
96
96
  await KeycloakManager.configure({
97
97
  baseUrl: 'http://localhost:8080', // Keycloak base URL
98
- realm: 'master', // Realm where the admin user belongs
98
+ realmName: 'master', // Realm where the admin user belongs (alias: realm)
99
99
  clientId: 'admin-cli', // Keycloak admin client
100
100
  username: 'admin', // Admin username
101
101
  password: 'admin', // Admin password
@@ -165,7 +165,7 @@ const KeycloakManager = require('keycloak-api-manager');
165
165
  // Initialize the manager with Keycloak credentials
166
166
  await KeycloakManager.configure({
167
167
  baseUrl: 'http://localhost:8080', // Keycloak base URL
168
- realm: 'master', // Realm where the admin user belongs
168
+ realmName: 'master', // Realm where the admin user belongs (alias: realm)
169
169
  clientId: 'admin-cli', // Keycloak admin client
170
170
  username: 'admin', // Admin username
171
171
  password: 'admin', // Admin password
@@ -186,7 +186,8 @@ Parameters:
186
186
  exposed by this adapter, so any attempt to call KeycloakManager.{function} will result in a runtime error due to access on an undefined object
187
187
  Main supported options:
188
188
  - baseUrl: [required] Keycloak base Url
189
- - 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'.
189
+ - 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'.
190
+ - realm: [optional] Alias of realmName for backward compatibility.
190
191
  - grantType: [required] The OAuth2 grant type used for authentication. example "password". Possible values: 'password', 'client_credentials', 'refresh_token', etc.
191
192
  - clientId: [required] string containing the client ID configured in Keycloak. Required for all grant types.
192
193
  - 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
@@ -200,6 +201,101 @@ Parameters:
200
201
  - refreshToken: [Optional] string containing a valid refresh token to request a new access token when using the refresh_token grant type.
201
202
  ---
202
203
 
204
+ ## 🧰 Available Helper Functions
205
+
206
+ ### `function setConfig(config)`
207
+ This function updates the runtime configuration of the Keycloak-api-manager Admin Client instance.
208
+ It allows switching the target realm, base URL, or HTTP request options without reinitializing the client or re-authenticating.
209
+ It’s useful when you need to interact with multiple realms or environments dynamically using the same admin client instance.
210
+
211
+ **` -- @parameters -- `**
212
+ - config: is a JSON object that accepts the following parameters:
213
+ - realmName: [optional] The name of the target realm for subsequent API requests.
214
+ - baseUrl: [optional] The base URL of the Keycloak server (e.g., https://auth.example.com).
215
+ - requestOptions: [optional] Custom HTTP options (headers, timeout, etc.) applied to API calls.
216
+ - realmPath: [optional] A custom realm path if your Keycloak instance uses a non-standard realm route.
217
+ - other fields
218
+
219
+ **` -- @notes -- `**
220
+ Calling setConfig does not perform authentication
221
+ - it only changes configuration values in memory.
222
+ - The authentication token already stored in the admin client remains active until it expires.
223
+ - Only the properties explicitly passed in the config object are updated; all others remain unchanged.
224
+
225
+ If the authenticated user does not have permissions in the new realmName, subsequent calls may fail with a 403 or 404.
226
+
227
+ Typically used in multi-realm or multi-environment management scripts.
228
+
229
+ ```js
230
+ const KcAdminClient = require('keycloak-api-manager');
231
+
232
+
233
+ // Switch context to another realm dynamically
234
+ kcAdminClient.setConfig({
235
+ realmName: 'customer-realm',
236
+ });
237
+
238
+ // All subsequent API calls will target "customer-realm"
239
+ const users = await kcAdminClient.users.find();
240
+ console.log(users);
241
+ ```
242
+
243
+ ### `function getToken()`
244
+ This function retrieves the current authentication tokens used by the Keycloak-api-manager Admin Client to communicate with the Keycloak REST API.
245
+ It returns both the access token (used for API authorization) and the refresh token (used to renew the session when the access token expires).
246
+
247
+ **` -- @returns -- `**
248
+ A JSON object containing:
249
+ - accessToken: The active access token string currently held by the Keycloak Admin Client.
250
+ - refreshToken: The corresponding refresh token string, if available, used to request a new access token without re-authentication.
251
+
252
+ **` -- @notes -- `**
253
+ The tokens are managed internally by the Keycloak Admin Client after successful authentication via kcAdminClient.auth().
254
+ The accessToken typically expires after a short period (e.g., 60 seconds by default).
255
+ You can use these tokens to call Keycloak REST endpoints manually or to debug authorization issues.
256
+ If the client is not authenticated or the session has expired, both values may be undefined.
257
+
258
+ ```js
259
+ const KcAdminClient = require('keycloak-api-manager');
260
+
261
+ // Example: retrieve and print current tokens
262
+ try {
263
+ const tokens = KcAdminClient.getToken();
264
+ console.log('Access Token:', tokens.accessToken);
265
+ console.log('Refresh Token:', tokens.refreshToken);
266
+ } catch (error) {
267
+ console.error('Failed to retrieve tokens:', error);
268
+ }
269
+
270
+ ```
271
+ ### `function auth(credentials)`
272
+ This function allows a user or client to authenticate against a Keycloak realm and obtain an access token (and optionally a refresh token).
273
+ It sends a direct HTTP POST request to the Keycloak OpenID Connect token endpoint using the provided credentials.
274
+
275
+ **` -- @parameters -- `**
276
+ credentials: a JSON object containing authentication details. Supported fields include:
277
+ - username: [optional] Username of the user (required for password grant).
278
+ - password: [optional] Password of the user (required for password grant).
279
+ - grant_type: [required] The OAuth2 grant type (e.g. "password", "client_credentials", "refresh_token").
280
+
281
+
282
+ ```js
283
+ const KeycloakManager = require('keycloak-api-manager');
284
+
285
+ // Example: authenticate a user via password grant
286
+ try {
287
+ const tokenResponse = await KeycloakManager.auth({
288
+ username: "demo",
289
+ password: "demo123",
290
+ grant_type: "password",
291
+ });
292
+
293
+ console.log("Access Token:", tokenResponse.access_token);
294
+ } catch (error) {
295
+ console.error("Authentication failed:", error);
296
+ }
297
+
298
+ ```
203
299
 
204
300
  ## 🔧 Available Admin Functions
205
301
  All administrative functions that rely on Keycloak's Admin API must be invoked using the
@@ -317,7 +413,7 @@ It’s useful for incremental updates or merging configuration pieces.
317
413
  **` -- @parameters -- `**
318
414
  - configuration: is a JSON object that accepts filter parameters
319
415
  - realm:[required] The name of the realm where the data should be imported.
320
- - representation:[required] A JSON object representing part of the realm configuration to be imported(can include users, roles, groups, clients, etc.).
416
+ - rep:[required] A JSON object representing part of the realm configuration to be imported(can include users, roles, groups, clients, etc.).
321
417
  - ifResourceExists:[required] Defines the behavior when an imported resource already exists in the target realm.
322
418
  Options are:
323
419
  - 'FAIL' – the operation fails if a resource already exists.
@@ -1855,7 +1951,10 @@ Creates a new client with the provided configuration
1855
1951
  ```js
1856
1952
  const KeycloakManager = require('keycloak-api-manager');
1857
1953
  // create a client called my-client
1858
- const client= await KeycloakManager.clients.create({name: "my-client", id:"client-id"});
1954
+ const client= await KeycloakManager.clients.create({
1955
+ name: "my-client",
1956
+ clientId:"client-id"
1957
+ });
1859
1958
  console.log("New Client Created:", client);
1860
1959
  ```
1861
1960
 
@@ -2238,7 +2337,7 @@ Default client scopes are automatically assigned to a client during token reques
2238
2337
 
2239
2338
  **` -- @parameters -- `**
2240
2339
  - filter: JSON structure that defines the filter parameters:
2241
- - id: [required] The client ID of the client whose default client scopes you want to list.
2340
+ - id: [required] The internal ID of the client whose default client scopes you want to list.
2242
2341
 
2243
2342
  ```js
2244
2343
  const KeycloakManager = require('keycloak-api-manager');
@@ -2258,7 +2357,7 @@ Optional scopes are those that a client can request explicitly but are not autom
2258
2357
 
2259
2358
  **` -- @parameters -- `**
2260
2359
  - filter: JSON structure that defines the filter parameters:
2261
- - id: [required] The client ID of the client whose optional client scopes you want to list.
2360
+ - id: [required] The internal ID of the client whose optional client scopes you want to list.
2262
2361
 
2263
2362
  ```js
2264
2363
  const KeycloakManager = require('keycloak-api-manager');
@@ -3943,7 +4042,7 @@ Client scopes are reusable sets of protocol mappers and role scope mappings whic
3943
4042
  can be assigned to clients to define what information about the user is included in tokens and what roles are available.
3944
4043
 
3945
4044
  #### `entity clientScopes functions`
3946
- ##### `function create(scopeRappresentation)`
4045
+ ##### `function create(scopeRepresentation)`
3947
4046
  method is used to create a new client scope in a Keycloak realm.
3948
4047
  A client scope defines a set of protocol mappers and roles that can be applied to clients,
3949
4048
  such as during login or token generation.
@@ -3958,7 +4057,7 @@ const KeycloakManager = require('keycloak-api-manager');
3958
4057
  ```
3959
4058
 
3960
4059
 
3961
- ##### `function update(filter,scopeRappresentation)`
4060
+ ##### `function update(filter,scopeRepresentation)`
3962
4061
  The method updates the configuration of an existing client scope in a realm.
3963
4062
  You can modify properties such as the scope’s name, description, attributes, or protocol mappers.
3964
4063
 
@@ -3966,7 +4065,7 @@ You can modify properties such as the scope’s name, description, attributes, o
3966
4065
  - filter: parameter provided as a JSON object that accepts the following filter:
3967
4066
  - id: [required] The unique ID of the client scope to update.
3968
4067
  - realm: [optional] The realm where the client scope exists.
3969
- - scopeRappresentation: The updated client scope object. for example:
4068
+ - scopeRepresentation: The updated client scope object. for example:
3970
4069
  - name: [optional] The name of the scope
3971
4070
  - description: [optional] The scope description
3972
4071
  - other scope fields....
@@ -4795,14 +4894,14 @@ These are providers like Google, Facebook, GitHub, SAML, OIDC, etc.
4795
4894
 
4796
4895
  #### `entity identityProviders functions`
4797
4896
 
4798
- ##### `function identityProviders.create(identityProvidersRappresentation)`
4897
+ ##### `function identityProviders.create(identityProvidersRepresentation)`
4799
4898
  The method is used to create a new Identity Provider (IdP) in a Keycloak realm.
4800
4899
  An IdP allows users to authenticate via external providers such as Google, Facebook, GitHub,
4801
4900
  or another SAML/OIDC provider.
4802
4901
  This method requires specifying an alias, the provider type, and configuration settings such as client ID, client secret, and any other provider-specific options.
4803
4902
 
4804
4903
  **` -- @parameters -- `**
4805
- - identityProvidersRappresentation: parameter provided as a JSON object containing the configuration of the Identity Provider
4904
+ - identityProvidersRepresentation: parameter provided as a JSON object containing the configuration of the Identity Provider
4806
4905
  - alias: [required] Unique name for the IdP within the realm.
4807
4906
  - providerId: [required] Type of provider (google, facebook, oidc, saml, etc.).
4808
4907
  - enabled: [optional] Whether the IdP is enabled. Default is true.
@@ -5185,7 +5284,7 @@ Groups are collections of users and can have roles and attributes assigned to th
5185
5284
  Groups help organize users and assign permissions in a scalable way
5186
5285
 
5187
5286
  #### `entity groups functions`
5188
- ##### `function create(groupRappresentation)`
5287
+ ##### `function create(groupRepresentation)`
5189
5288
  Create a new group in the current realme
5190
5289
 
5191
5290
  **` -- @parameters -- `**
@@ -5637,7 +5736,7 @@ Get a role by its Id
5637
5736
 
5638
5737
  **` -- @parameters -- `**
5639
5738
  - filters: parameter provided as a JSON object that accepts the following parameters:
5640
- - Id (string, required) — The Id of the role to retrieve.
5739
+ - id (string, required) — The id of the role to retrieve.
5641
5740
  - realm (string, optional if set globally) — The realm where the role is defined.
5642
5741
  ```js
5643
5742
  const KeycloakManager = require('keycloak-api-manager');
@@ -5664,7 +5763,7 @@ Update a role by its Id
5664
5763
 
5665
5764
  **` -- @parameters -- `**
5666
5765
  - filters: parameter provided as a JSON object that accepts the following parameters:
5667
- - name (string, required) — The exact name of the role to retrieve.
5766
+ - id (string, required) — The id of the role to retrieve.
5668
5767
  - realm (string, optional if set globally) — The realm where the role is defined.
5669
5768
  - role_dictionary: A JSON object representing a role dictionary as defined in Keycloak
5670
5769
  ```js
@@ -6194,7 +6293,7 @@ This allows you to modify settings such as OTP policies, password requirements,
6194
6293
  **` -- @parameters -- `**
6195
6294
  - filter: parameter provided as a JSON object that accepts the following filter:
6196
6295
  - alias: [required] The alias (providerId) of the required action to update.
6197
- - actionRepresentation: The configuration object to update.
6296
+ - actionConfigRepresentation: The configuration object to update.
6198
6297
 
6199
6298
 
6200
6299
  ```js
@@ -0,0 +1,27 @@
1
+ version: '3.8'
2
+
3
+ services:
4
+ keycloak:
5
+ image: keycloak/keycloak:latest
6
+ container_name: keycloak-test
7
+ ports:
8
+ - "8080:8080"
9
+ environment:
10
+ KEYCLOAK_ADMIN: admin
11
+ KEYCLOAK_ADMIN_PASSWORD: admin
12
+ KC_DB: dev-mem
13
+ KC_METRICS_ENABLED: 'false'
14
+ KC_HEALTH_ENABLED: 'true'
15
+ command:
16
+ - start-dev
17
+ healthcheck:
18
+ test: ["CMD", "curl", "-f", "http://localhost:8080/health/ready"]
19
+ interval: 5s
20
+ timeout: 5s
21
+ retries: 12
22
+ networks:
23
+ - keycloak-network
24
+
25
+ networks:
26
+ keycloak-network:
27
+ driver: bridge
package/index.js CHANGED
@@ -96,7 +96,7 @@ exports.setConfig=function(configToOverride){
96
96
  }
97
97
  //TODO: Remove da documentare
98
98
  // restituisce il token utilizzato dalla libreria per comunicare con la keycloak API
99
- exports.getToken=function(configToOverride){
99
+ exports.getToken=function(){
100
100
  return({
101
101
  accessToken:kcAdminClient.accessToken,
102
102
  refreshToken:kcAdminClient.refreshToken,
package/index.mjs ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * ESM wrapper for keycloak-api-manager
3
+ * This file provides ES Module support while the core is still CommonJS
4
+ */
5
+
6
+ import { createRequire } from 'module';
7
+ import { fileURLToPath } from 'url';
8
+ import path from 'path';
9
+
10
+ const require = createRequire(import.meta.url);
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = path.dirname(__filename);
13
+
14
+ const keycloakApiManager = require('./index.js');
15
+
16
+ export const configure = keycloakApiManager.configure;
17
+ export const setConfig = keycloakApiManager.setConfig;
18
+ export const getToken = keycloakApiManager.getToken;
19
+ export const auth = keycloakApiManager.auth;
20
+
21
+ export default keycloakApiManager;
package/package.json CHANGED
@@ -1,10 +1,17 @@
1
1
  {
2
2
  "name": "keycloak-api-manager",
3
- "version": "3.1.0",
3
+ "version": "3.2.1",
4
4
  "description": "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 like you would from the Keycloak admin console.",
5
5
  "main": "index.js",
6
+ "exports": {
7
+ ".": {
8
+ "import": "./index.mjs",
9
+ "require": "./index.js"
10
+ }
11
+ },
6
12
  "scripts": {
7
- "test": "mocha"
13
+ "test": "mocha",
14
+ "test:watch": "mocha --watch --watch-extensions js"
8
15
  },
9
16
  "dependencies": {
10
17
  "@keycloak/keycloak-admin-client": "^26.3.2",
@@ -23,6 +30,11 @@
23
30
  "serve-favicon": "^2.5.0",
24
31
  "underscore": "^1.13.7"
25
32
  },
33
+ "devDependencies": {
34
+ "chai": "^4.3.10",
35
+ "mocha": "^10.2.0",
36
+ "dockerode": "^4.0.2"
37
+ },
26
38
  "keywords": [
27
39
  "keycloak",
28
40
  "user",