keycloak-express-middleware 2.0.3 โ 3.0.0
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/README.md +110 -187
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
# ๐ Keycloak
|
|
2
|
-
|
|
1
|
+
# ๐ Keycloak Express middleware for Node.js (Express)
|
|
3
2
|
An adapter API to seamlessly integrate **Node.js Express** applications with **Keycloak** for authentication and authorization using **OpenID Connect (OIDC)**.
|
|
3
|
+
This middleware provides route protection, token validation, user role management. Ideal for securing RESTful services, microservices, Express-based backends, and express or javascript frontends.
|
|
4
|
+
it is based on **'keycloak-connect'**, and **'express-session'**
|
|
4
5
|
|
|
5
|
-
This middleware provides route protection, token validation, user role management, and easy access to Keycloak-secured APIs. Ideal for securing RESTful services, microservices, and Express-based backends.
|
|
6
|
-
it is based on 'keycloak-connect', 'express-session' and '@keycloak/keycloak-admin-client'
|
|
7
|
-
---
|
|
8
6
|
|
|
7
|
+
---
|
|
9
8
|
## ๐ฆ Features
|
|
10
|
-
|
|
11
9
|
- ๐ OIDC-based authentication with Keycloak
|
|
12
10
|
- ๐งพ Access token validation (JWT)
|
|
13
11
|
- ๐ Route protection via role-based access control
|
|
@@ -15,28 +13,19 @@ it is based on 'keycloak-connect', 'express-session' and '@keycloak/keycloak-adm
|
|
|
15
13
|
- โ๏ธ Configurable Keycloak client and realm settings
|
|
16
14
|
- ๐ค User info extraction from token
|
|
17
15
|
- ๐ CORS support and integration with frontend apps (SPA or mobile)
|
|
18
|
-
|
|
19
16
|
---
|
|
20
|
-
|
|
21
17
|
## ๐ Installation
|
|
22
|
-
|
|
23
18
|
```bash
|
|
24
19
|
npm install keycloak-express-middleware
|
|
25
20
|
```
|
|
26
|
-
|
|
27
21
|
Or, if using Yarn:
|
|
28
|
-
|
|
29
22
|
```bash
|
|
30
23
|
yarn add keycloak-express-middleware
|
|
31
24
|
```
|
|
32
|
-
|
|
33
25
|
---
|
|
34
|
-
|
|
35
26
|
## ๐ ๏ธ Get Keycloak Configuration
|
|
36
|
-
|
|
37
27
|
Copy or Download from keycloak admin page your client configuration `keycloak.json` by visiting
|
|
38
28
|
the Keycloak Admin Console โ clients (left sidebar) โ choose your client โ Installation โ Format Option โ Keycloak OIDC JSON โ Download
|
|
39
|
-
|
|
40
29
|
```json
|
|
41
30
|
{
|
|
42
31
|
"realm": "your-realm",
|
|
@@ -49,14 +38,11 @@ the Keycloak Admin Console โ clients (left sidebar) โ choose your client โ
|
|
|
49
38
|
"confidential-port": 0
|
|
50
39
|
}
|
|
51
40
|
```
|
|
52
|
-
|
|
53
41
|
---
|
|
54
|
-
|
|
55
42
|
## ๐ Usage Example
|
|
56
|
-
|
|
57
43
|
```js
|
|
58
44
|
const express = require('express');
|
|
59
|
-
const keycloackAdapter = require('keycloak-
|
|
45
|
+
const keycloackAdapter = require('keycloak-express-middleware');
|
|
60
46
|
|
|
61
47
|
const app = express();
|
|
62
48
|
|
|
@@ -79,12 +65,13 @@ await keycloackAdapter.configure(app,{
|
|
|
79
65
|
});
|
|
80
66
|
|
|
81
67
|
|
|
82
|
-
// Public route
|
|
68
|
+
// -------------- Public route -----------------------
|
|
83
69
|
app.get('/', (req, res) => {
|
|
84
70
|
res.send('Public route: no authentication required');
|
|
85
71
|
});
|
|
86
72
|
|
|
87
|
-
|
|
73
|
+
|
|
74
|
+
/* ############## Protected routes (any authenticated user) ########### */
|
|
88
75
|
|
|
89
76
|
// Example of login with keycloackAdapter.login function
|
|
90
77
|
// After login redirect to "/home"
|
|
@@ -183,8 +170,12 @@ app.get('/encodeToken', keycloackAdapter.encodeTokenRole(), (req, res) => {
|
|
|
183
170
|
|
|
184
171
|
});
|
|
185
172
|
|
|
186
|
-
|
|
187
|
-
//
|
|
173
|
+
|
|
174
|
+
// #####################################################################################
|
|
175
|
+
// # This section provides examples of how to protect resources based on permissions #
|
|
176
|
+
// # rather than roles. #
|
|
177
|
+
// #####################################################################################
|
|
178
|
+
|
|
188
179
|
|
|
189
180
|
// Example of protection with keycloackAdapter.enforcerMiddleware middleware
|
|
190
181
|
// whith a static control string
|
|
@@ -255,15 +246,11 @@ app.listen(PORT, () => {
|
|
|
255
246
|
console.log(`Server running at http://localhost:${PORT}`);
|
|
256
247
|
});
|
|
257
248
|
```
|
|
258
|
-
|
|
259
249
|
---
|
|
260
|
-
|
|
261
250
|
## ๐งฉ Configuration
|
|
262
|
-
|
|
263
251
|
In your Express application:
|
|
264
|
-
|
|
265
252
|
```js
|
|
266
|
-
import keycloakAdapter from 'keycloak-
|
|
253
|
+
import keycloakAdapter from 'keycloak-express-middleware';
|
|
267
254
|
|
|
268
255
|
// Configure and Initialize Keycloak adapter
|
|
269
256
|
keycloackAdapter.configure(app,{
|
|
@@ -282,94 +269,55 @@ keycloackAdapter.configure(app,{
|
|
|
282
269
|
}
|
|
283
270
|
})
|
|
284
271
|
```
|
|
285
|
-
|
|
286
272
|
keycloackAdapter.configure is a configuration function for the Keycloak
|
|
287
|
-
adapter in an Express application.
|
|
288
|
-
It must be called at app startup, before defining any protected routes.
|
|
273
|
+
adapter in an Express application. It must be called at app startup, before defining any protected routes.
|
|
289
274
|
It is an async function and returns a promise
|
|
290
275
|
|
|
291
|
-
|
|
292
|
-
- app
|
|
293
|
-
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
Example:
|
|
276
|
+
**` -- @parameters -- `**
|
|
277
|
+
- **app**: `[required]` Express application instance (e.g., const app = express();)
|
|
278
|
+
- **keyCloakConfig:** `[required]`JSON object containing the Keycloak client configuration. This can be obtained from the Keycloak admin console: Clients โ [client name] โ Installation โ "Keycloak OIDC JSON" โ Download
|
|
279
|
+
Example:
|
|
280
|
+
```js
|
|
297
281
|
{
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
282
|
+
"realm": "realm-name",
|
|
283
|
+
"auth-server-url": "https://keycloak.example.com/",
|
|
284
|
+
"ssl-required": "external",
|
|
285
|
+
"resource": "client-name",
|
|
286
|
+
"credentials": { "secret": "secret-code" },
|
|
287
|
+
"confidential-port": 0
|
|
304
288
|
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
- cookies: to enable cookie handling
|
|
313
|
-
- realmUrl: to override the realm URL
|
|
314
|
-
- adminClientCredentials: [Optional] Advanced configuration for setting up the realm-admin user or client,
|
|
315
|
-
which will be used as the administrator to manage Keycloak via API.
|
|
316
|
-
This is required in order to use the administrative functions exposed by this library.
|
|
317
|
-
If this parameter is not provided, it will not be possible to use the administrative functions of Keycloak
|
|
318
|
-
exposed by this adapter. In fact, exports.kcAdminClient will be null, so any attempt to call
|
|
319
|
-
keycloakAdapter.kcAdminClient will result in a runtime error due to access on an undefined object
|
|
320
|
-
Main supported options:
|
|
321
|
-
- realmName: [Optional] A String that specifies the realm to authenticate against, if different from the "keyCloakConfig.realm" parameter.
|
|
322
|
-
If you intend to use Keycloak administrator credentials, this should be set to 'master'.
|
|
323
|
-
- scope: [Optional] A string that specifies The OAuth2 scope requested during authentication (optional).
|
|
324
|
-
Typically, not required for administrative clients. example:openid profile
|
|
325
|
-
- requestOptions: [Optional] JSON parameters to configure HTTP requests (such as custom headers, timeouts, etc.).
|
|
326
|
-
It is compatible with the Fetch API standard. Fetch request options
|
|
327
|
-
https://developer.mozilla.org/en-US/docs/Web/API/fetch#options
|
|
328
|
-
- username: [Optional] string username. Required when using the password grant type.
|
|
329
|
-
- password: [Optional] string password. Required when using the password grant type.
|
|
330
|
-
- grantType: The OAuth2 grant type used for authentication.
|
|
331
|
-
Possible values: 'password', 'client_credentials', 'refresh_token', etc.
|
|
332
|
-
- clientId: string containing the client ID configured in Keycloak. Required for all grant types.
|
|
333
|
-
- clientSecret: [Optional] string containing the client secret of the client. Required for client_credentials or confidential clients.
|
|
334
|
-
- totp: string for Time-based One-Time Password (TOTP) for multifactor authentication (MFA), if enabled for the user.
|
|
335
|
-
- offlineToken: [Optional] boolean value. If true, requests an offline token (used for long-lived refresh tokens). Default is false.
|
|
336
|
-
- refreshToken: [Optional] string containing a valid refresh token to request a new access token when using the refresh_token grant type.
|
|
289
|
+
```
|
|
290
|
+
- **keyCloakOptions**: `[required]` advanced configuration options for the adapter. Main supported options:
|
|
291
|
+
- **session:** Express session configuration (as in express-session)
|
|
292
|
+
- **scope:** authentication scopes (e.g., 'openid profile email offline_access') **Note:** to use offline_access, the client must have the option enabled and the user must have the offline_access role.
|
|
293
|
+
- **idpHint:** to suggest an identity provider to Keycloak during login
|
|
294
|
+
- **cookies:** to enable cookie handling
|
|
295
|
+
- **realmUrl:** to override the realm URL
|
|
337
296
|
---
|
|
338
|
-
|
|
339
297
|
## ๐ง Available Middlewares
|
|
340
|
-
|
|
341
298
|
### `underKeycloakProtection(callback) - deprecated - `
|
|
342
|
-
|
|
343
|
-
then define your resources as you normally would in Express:
|
|
299
|
+
**@deprecated Method**. Use the `configure` Method with await keycloakAdapter.configure(...)`, then define your resources as you normally would in Express:
|
|
344
300
|
```js
|
|
345
301
|
await keycloakAdapter.configure(config_Parameters);
|
|
346
302
|
|
|
347
|
-
// all your routes
|
|
303
|
+
// Define all your routes here
|
|
348
304
|
|
|
349
305
|
app.get('/my-route', handler);
|
|
350
306
|
```
|
|
351
|
-
|
|
352
|
-
Alternatively, if you prefer to define your resources inside a container after configuration,
|
|
353
|
-
you can use the `then` syntax:
|
|
307
|
+
Alternatively, if you prefer to define your resources inside a container after configuration, you can use the `then` syntax:
|
|
354
308
|
```js
|
|
355
309
|
keycloakAdapter.configure(configParameters).then(() => {
|
|
356
|
-
// Define all your routes here
|
|
310
|
+
// Define all your routes to protect here
|
|
357
311
|
app.get('/my-route', handler);
|
|
358
312
|
});
|
|
359
313
|
```
|
|
314
|
+
This Method is deprecated and will be removed in future versions. It must be called **after** Keycloak has been configured with `configure()`.
|
|
315
|
+
The routes declared inside the provided callback will be protected and will have access to authentication/authorization features managed by Keycloak.
|
|
360
316
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
Method to define Express routes that must be protected by Keycloak.
|
|
364
|
-
|
|
365
|
-
This method must be called **after** Keycloak has been configured with `configure()`.
|
|
366
|
-
The routes declared inside the provided callback will be protected and will have access
|
|
367
|
-
to authentication/authorization features managed by Keycloak.
|
|
368
|
-
|
|
369
|
-
๐ Public (unprotected) routes should be declared **before** calling this method.
|
|
317
|
+
๐ Public (unprotected) routes should be declared **before** calling this method.
|
|
370
318
|
|
|
371
|
-
|
|
372
|
-
It must contain exclusively routes requiring authentication.
|
|
319
|
+
**` -- @parameters -- `**
|
|
320
|
+
- **{Function} callback:** `[required]` A function that defines all routes to be protected. It must contain exclusively routes requiring authentication.
|
|
373
321
|
|
|
374
322
|
โ
Usage example:
|
|
375
323
|
```js
|
|
@@ -396,30 +344,25 @@ keycloakAdapter.underKeycloakProtection(() => {
|
|
|
396
344
|
});
|
|
397
345
|
});
|
|
398
346
|
```
|
|
399
|
-
|
|
347
|
+
---
|
|
400
348
|
### `protectMiddleware([conditions])`
|
|
401
|
-
Middleware to protect Express routes based on authentication and, optionally,
|
|
402
|
-
|
|
349
|
+
Middleware to protect Express routes based on authentication and, optionally, authorization via Keycloak roles.
|
|
350
|
+
Allows restricting access to a resource only to authenticated users or to those possessing specific roles in the realm or in a Keycloak client.
|
|
403
351
|
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
@param {string|function} [conditions]
|
|
408
|
-
- If a string, specifies one or more required roles, using the syntax:
|
|
352
|
+
**` -- @parameters -- `**
|
|
353
|
+
- **conditions**: `[optional]` An array of strings each specifying one or more required roles; or a function executing custom code performing an access role verification
|
|
354
|
+
- As array of strings: specifies one or more required roles, using the syntax:
|
|
409
355
|
- 'role' โ client role in the configured client (e.g., 'admin')
|
|
410
356
|
- 'clientid:role' โ client role of a specific client (e.g., 'myclient:editor')
|
|
411
357
|
- 'realm:role' โ realm role (e.g., 'realm:superuser')
|
|
412
|
-
-
|
|
413
|
-
|
|
414
|
-
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
- token.hasRole('my-client:editor') // client role of a specific client
|
|
418
|
-
- token.hasResourceRole('editor', 'my-client-id') // equivalent to hasRole('my-client:editor')
|
|
419
|
-
|
|
358
|
+
- As a function: receives (token, req) and must return true or false synchronously. This function enables custom authorization logic. The `token` object passed to the authorization function exposes methods such as:
|
|
359
|
+
- token.hasRole('admin') // client role in configured client
|
|
360
|
+
- token.hasRole('realm:superuser') // realm role
|
|
361
|
+
- token.hasRole('my-client:editor') // client role of a specific client
|
|
362
|
+
- token.hasResourceRole('editor', 'my-client-id') // equivalent to hasRole('my-client:editor')
|
|
420
363
|
The authorization function must be synchronous and return true (allow access) or false (deny access).
|
|
421
364
|
|
|
422
|
-
@returns
|
|
365
|
+
**` -- @returns -- `** It return a function as an Express middleware to protect the route.
|
|
423
366
|
|
|
424
367
|
โ
Usage example:
|
|
425
368
|
```js
|
|
@@ -452,13 +395,10 @@ app.get('/custom', keycloakAdapter.protectMiddleware((token, req) => {
|
|
|
452
395
|
}), (req, res) => {
|
|
453
396
|
res.send('Access granted by custom authorization function.');
|
|
454
397
|
});
|
|
455
|
-
|
|
456
398
|
```
|
|
457
|
-
|
|
458
|
-
|
|
399
|
+
---
|
|
459
400
|
### `customProtectMiddleware(fn)`
|
|
460
401
|
Middleware similar to `protectMiddleware` but with dynamic role checking via a function.
|
|
461
|
-
|
|
462
402
|
Unlike `protectMiddleware`, which accepts a string expressing the role or a control function
|
|
463
403
|
that works on the token, this middleware accepts a function that receives the Express
|
|
464
404
|
request and response objects `req` and `res` and must return a string representing the role control string.
|
|
@@ -466,15 +406,12 @@ request and response objects `req` and `res` and must return a string representi
|
|
|
466
406
|
This is useful for parametric resources where the role control string must be dynamically generated based on the request,
|
|
467
407
|
for example, based on URL parameters or query strings.
|
|
468
408
|
|
|
469
|
-
Note
|
|
470
|
-
so it cannot be used for complex logic depending on request properties other than the role
|
|
471
|
-
(e.g., client IP, custom headers, etc.).
|
|
409
|
+
**Note:** this function **does not** access or parse the token, nor performs any checks other than the role,
|
|
410
|
+
so it cannot be used for complex logic depending on request properties other than the role (e.g., client IP, custom headers, etc.).
|
|
472
411
|
The function's sole task is to generate the role control string.
|
|
473
412
|
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
@param {function} customFunction - function that receives (req, res) and returns a string
|
|
477
|
-
with the role control string to pass to Keycloak.
|
|
413
|
+
**` -- @parameters -- `**
|
|
414
|
+
- **fn:** `[required]` Custom function that receives (req, res) and returns a string with the role control string to pass to Keycloak.
|
|
478
415
|
|
|
479
416
|
โ
Usage example:
|
|
480
417
|
```js
|
|
@@ -486,11 +423,10 @@ app.get('/custom/:id', keycloakAdapter.customProtectMiddleware((req) => {
|
|
|
486
423
|
res.send(`Access granted to users with role 'clientRole${req.params.id}'`);
|
|
487
424
|
});
|
|
488
425
|
```
|
|
489
|
-
|
|
490
|
-
|
|
426
|
+
---
|
|
491
427
|
### `enforcerMiddleware(conditions, options)`
|
|
492
|
-
`enforcerMiddleware` is a middleware to enable permission checks
|
|
493
|
-
|
|
428
|
+
`enforcerMiddleware` is a middleware to enable permission checks based on resources and policies
|
|
429
|
+
defined in Keycloak Authorization Services (UMA 2.0-based).
|
|
494
430
|
|
|
495
431
|
Unlike `protectMiddleware` and similar, which only verify authentication or roles,
|
|
496
432
|
`enforcerMiddleware` allows checking if the user has permission to access
|
|
@@ -499,20 +435,18 @@ a specific protected resource through flexible and dynamic policies.
|
|
|
499
435
|
Useful in contexts where resources are registered in Keycloak (such as documents, instances, dynamic entities) and
|
|
500
436
|
protected by flexible policies.
|
|
501
437
|
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
-
|
|
514
|
-
- claims: object with claim info for dynamic policies (e.g. owner id matching)
|
|
515
|
-
- resource_server_id: resource client id (default: current client)
|
|
438
|
+
**` -- @parameters -- `**
|
|
439
|
+
- **conditions:** a check control string or function
|
|
440
|
+
- ***As a string:*** contain the name of the resource or permission to check
|
|
441
|
+
- ***as a function:*** custom check function with signature:
|
|
442
|
+
***`function(token, req, callback)`***
|
|
443
|
+
- token: decoded Keycloak token
|
|
444
|
+
- req: Express request
|
|
445
|
+
- callback(boolean): invoke with true if authorized, false otherwise
|
|
446
|
+
- **options:**: parameter provided as a JSON object that accepts the following filter:
|
|
447
|
+
- response_mode: 'permissions' (default) or 'token'
|
|
448
|
+
- claims: object with claim info for dynamic policies (e.g. owner id matching)
|
|
449
|
+
- resource_server_id: resource client id (default: current client)
|
|
516
450
|
|
|
517
451
|
--- How it works ---
|
|
518
452
|
- If conditions is a function, it is used for custom checks with callback.
|
|
@@ -562,7 +496,7 @@ app.get('/onlyAdminrouteByfunction', keycloakAdapter.enforcerMiddleware(function
|
|
|
562
496
|
res.send('You are an authorized admin or viewer (custom check)');
|
|
563
497
|
});
|
|
564
498
|
```
|
|
565
|
-
|
|
499
|
+
---
|
|
566
500
|
### `customEnforcerMiddleware(fn, options)`
|
|
567
501
|
`customEnforcerMiddleware` is a middleware for permission checks based on resources and policies
|
|
568
502
|
defined in Keycloak Authorization Services (UMA 2.0), using dynamic permission strings.
|
|
@@ -571,23 +505,20 @@ This middleware is similar to `enforcerMiddleware`, but takes a function
|
|
|
571
505
|
`customFunction(req, res)` as a parameter, which must dynamically return
|
|
572
506
|
the permission/resource string to be checked.
|
|
573
507
|
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
}
|
|
584
|
-
```
|
|
508
|
+
**` -- @parameters -- `**
|
|
509
|
+
- **fn:**`[required]` custom function that receives `req` and `res` and returns the control string for Keycloak.
|
|
510
|
+
As example:
|
|
511
|
+
```js
|
|
512
|
+
function customFunction(req, res) {
|
|
513
|
+
// Your function logic
|
|
514
|
+
return req.params.permission;
|
|
515
|
+
}
|
|
516
|
+
```
|
|
585
517
|
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
- resource_server_id: string representing the resource client ID (default: current client)
|
|
518
|
+
- **options:** `[optional]` Additional options passed to `keycloak.enforcer()`, including:
|
|
519
|
+
- **response_mode:** 'permissions' (default) or 'token'
|
|
520
|
+
- **claims:** object with claim info for dynamic policies (e.g., owner ID)
|
|
521
|
+
- **resource_server_id:** string representing the resource client ID (default: current client)
|
|
591
522
|
|
|
592
523
|
--- response_mode options ---
|
|
593
524
|
1) 'permissions' (default)
|
|
@@ -619,11 +550,12 @@ const tmpFunctionEnforce = function(req, res) {
|
|
|
619
550
|
};
|
|
620
551
|
|
|
621
552
|
app.get('/onlyAdminrouteByfunction/:permission', keycloakAdapter.customEnforcerMiddleware(tmpFunctionEnforce), (req, res) => {
|
|
553
|
+
console.log("token permissions:", req.permissions);
|
|
622
554
|
res.send('You are an authorized user with dynamic permission: ' + req.params.permission);
|
|
623
555
|
});
|
|
624
556
|
|
|
625
557
|
```
|
|
626
|
-
|
|
558
|
+
---
|
|
627
559
|
### `encodeTokenRole()`
|
|
628
560
|
`encodeTokenRole` is a middleware that decodes the Keycloak token and adds it
|
|
629
561
|
to the Express request as `req.encodedTokenRole`.
|
|
@@ -656,7 +588,7 @@ app.get('/encodeToken', keycloakAdapter.encodeTokenRole(), (req, res) => {
|
|
|
656
588
|
});
|
|
657
589
|
|
|
658
590
|
```
|
|
659
|
-
|
|
591
|
+
---
|
|
660
592
|
### `encodeTokenPermission()`
|
|
661
593
|
`encodeTokenPermission` ia s Middleware whose sole purpose is to decode the access token present in the request
|
|
662
594
|
and add to the `req` object a property called `encodedTokenPermission` containing the token's permissions.
|
|
@@ -672,12 +604,8 @@ It is particularly useful when:
|
|
|
672
604
|
|
|
673
605
|
--- Additions to `req` ---
|
|
674
606
|
|
|
675
|
-
After applying the middleware, `req` contains:
|
|
676
|
-
-
|
|
677
|
-
An object exposing the method:
|
|
678
|
-
- hasPermission(permission: string, callback: function(boolean))
|
|
679
|
-
Checks whether the token contains the specified permission.
|
|
680
|
-
The callback receives `true` if the permission is present, `false` otherwise.
|
|
607
|
+
After applying the middleware, `req` contains the property **`encodedTokenPermission`** as an object exposing the method:
|
|
608
|
+
- hasPermission(permission: string, callback: function(boolean)) :Checks whether the token contains the specified permission. The callback receives `true` if the permission is present, `false` otherwise.
|
|
681
609
|
|
|
682
610
|
โ
Usage example:
|
|
683
611
|
```js
|
|
@@ -694,7 +622,7 @@ app.get('/encodeTokenPermission',
|
|
|
694
622
|
});
|
|
695
623
|
|
|
696
624
|
```
|
|
697
|
-
|
|
625
|
+
---
|
|
698
626
|
### `loginMiddleware(redirectTo)`
|
|
699
627
|
`loginMiddleware` is a Middleware used to **force user authentication** via Keycloak.
|
|
700
628
|
|
|
@@ -709,9 +637,8 @@ It is particularly useful when you want to:
|
|
|
709
637
|
2. If authentication fails or is denied, the user is redirected according to Keycloak's configured settings.
|
|
710
638
|
3. If authentication is successful, the user is redirected to 'redirectTo' (usually `/home`, `/dashboard`, etc.).
|
|
711
639
|
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
@param {string} redirectTo - URL to redirect the user to after login.
|
|
640
|
+
**` -- @parameters -- `**
|
|
641
|
+
- **redirectTo**: `[required]` URL to redirect the user to after login.
|
|
715
642
|
|
|
716
643
|
--- Warning ---
|
|
717
644
|
|
|
@@ -727,8 +654,7 @@ app.get('/loginMiddleware', keycloakAdapter.loginMiddleware("/home"), (req, res)
|
|
|
727
654
|
});
|
|
728
655
|
|
|
729
656
|
```
|
|
730
|
-
|
|
731
|
-
|
|
657
|
+
---
|
|
732
658
|
### `logoutMiddleware(redirectTo)`
|
|
733
659
|
`logoutMiddleware` Middleware is used to **force user logout**, removing the local session
|
|
734
660
|
and redirecting the user to Keycloak's logout endpoint according to its configuration.
|
|
@@ -744,9 +670,8 @@ It is useful when:
|
|
|
744
670
|
3. **Destroys the local Express session** (e.g., cookies, user data).
|
|
745
671
|
4. Redirects the user to the Keycloak logout URL, which in turn redirects to the provided URL.
|
|
746
672
|
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
@param {string} redirectTo - URL to which the user will be redirected after complete logout.
|
|
673
|
+
**` -- @parameters -- `**
|
|
674
|
+
- **redirectTo**: `[required]` URL to which the user will be redirected after complete logout.
|
|
750
675
|
|
|
751
676
|
โ
Usage example:
|
|
752
677
|
```js
|
|
@@ -757,7 +682,6 @@ app.get('/logoutMiddleware', keycloakAdapter.logoutMiddleware("http://localhost:
|
|
|
757
682
|
});
|
|
758
683
|
|
|
759
684
|
```
|
|
760
|
-
|
|
761
685
|
--- Note ---
|
|
762
686
|
- The middleware **never executes the route callback**, as it fully handles the response.
|
|
763
687
|
- The `redirectTo` parameter must match a **valid redirect URI** configured in Keycloak for the client.
|
|
@@ -768,7 +692,6 @@ app.get('/logoutMiddleware', keycloakAdapter.logoutMiddleware("http://localhost:
|
|
|
768
692
|
|
|
769
693
|
|
|
770
694
|
## ๐ง Available Functions
|
|
771
|
-
|
|
772
695
|
### `login(req, res, redirectTo)`
|
|
773
696
|
`login` Function not a middleware, but a **classic synchronous function** that forces user authentication
|
|
774
697
|
via Keycloak and, if the user is not authenticated, redirects them to the login page.
|
|
@@ -779,11 +702,10 @@ After successful login, the user is redirected to the URL specified in the `redi
|
|
|
779
702
|
- `login` instead is a function **that can be manually called inside the route handler**,
|
|
780
703
|
offering **greater control** over when and how login is enforced.
|
|
781
704
|
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
-
|
|
785
|
-
-
|
|
786
|
-
- @param {string} redirectTo - URL to redirect the user to after successful login
|
|
705
|
+
**` -- @parameters -- `**
|
|
706
|
+
- **req:** `[required]` Express `Request` object
|
|
707
|
+
- **res:** `[required]` Express `Response` object
|
|
708
|
+
- **redirectTo:** `[required]` URL to redirect the user to after successful login
|
|
787
709
|
|
|
788
710
|
--- Behavior ---
|
|
789
711
|
1. Attempts to protect the request using `keycloak.protect()`.
|
|
@@ -808,7 +730,7 @@ app.get('/login', (req, res) => {
|
|
|
808
730
|
|
|
809
731
|
--- Requirements ---
|
|
810
732
|
- `Valid Redirect URIs` must include the URL passed to `redirectTo`.
|
|
811
|
-
|
|
733
|
+
---
|
|
812
734
|
### `logout(req, res, redirectTo)`
|
|
813
735
|
`logout` Function is not a middleware, but a **classic synchronous function** that forces the user to logout
|
|
814
736
|
via Keycloak. In addition to terminating the current session (if any), it generates the Keycloak
|
|
@@ -819,10 +741,11 @@ logout URL and redirects the user's browser to that address.
|
|
|
819
741
|
- `logout` instead is a function **to be called inside the route**, useful for handling logout
|
|
820
742
|
**conditionally** or within more complex logic.
|
|
821
743
|
|
|
822
|
-
|
|
823
|
-
-
|
|
824
|
-
-
|
|
825
|
-
-
|
|
744
|
+
**` -- @parameters -- `**
|
|
745
|
+
- **req:** `[required]` Express `Request` object
|
|
746
|
+
- **res:** `[required]` Express `Response` object
|
|
747
|
+
- **redirectTo:** `[required]` URL to redirect the user to after successful logout
|
|
748
|
+
|
|
826
749
|
|
|
827
750
|
--- Behavior ---
|
|
828
751
|
1. Retrieves the `id_token` from the current user's Keycloak token (if present).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keycloak-express-middleware",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "Adapter API to integrate Node.js (Express) applications with Keycloak. Provides middleware for authentication, authorization, token validation, and route protection via OpenID Connect.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|