keycloak-express-middleware 6.1.0 → 6.1.2

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.
Files changed (41) hide show
  1. package/MIGRATION_STATUS.md +46 -160
  2. package/OIDC_INTEGRATION_GUIDE.md +15 -243
  3. package/README.md +1072 -643
  4. package/config/default.json +18 -0
  5. package/docs/MIGRATION_STATUS.md +48 -0
  6. package/docs/OIDC_INTEGRATION_GUIDE.md +254 -0
  7. package/docs/README.md +38 -0
  8. package/docs/api/authorization-services.md +121 -0
  9. package/docs/api/configuration.md +116 -0
  10. package/docs/api/oidc-token-endpoint.md +148 -0
  11. package/docs/api/route-protection.md +122 -0
  12. package/docs/api/session-and-navigation.md +138 -0
  13. package/docs/api/token-decode-helpers.md +94 -0
  14. package/docs/api-reference.md +96 -0
  15. package/docs/architecture.md +97 -0
  16. package/docs/deployment.md +144 -0
  17. package/docs/keycloak-setup.md +203 -0
  18. package/docs/test-configuration.md +316 -0
  19. package/docs/testing-environment.md +142 -0
  20. package/docs/testing.md +413 -0
  21. package/index.js +75 -669
  22. package/oidc-methods.js +13 -13
  23. package/package.json +10 -2
  24. package/test/.mocharc.json +9 -0
  25. package/test/config/default.json +15 -0
  26. package/test/config/secrets.json.example +12 -0
  27. package/test/docker-keycloak/README.md +472 -0
  28. package/test/docker-keycloak/certs/.gitkeep +0 -0
  29. package/test/docker-keycloak/certs/README.md +82 -0
  30. package/test/docker-keycloak/docker-compose-https.yml +46 -0
  31. package/test/docker-keycloak/docker-compose.yml +45 -0
  32. package/test/docker-keycloak/setup-keycloak.js +540 -0
  33. package/test/helpers/config.js +41 -0
  34. package/test/helpers/keycloak-setup.js +104 -0
  35. package/test/keycloak-integration.test.js +84 -0
  36. package/test/oidc-methods.test.js +8 -8
  37. package/test/package-lock.json +2895 -0
  38. package/test/package.json +22 -0
  39. package/test/support/enableServerFeatures.js +127 -0
  40. package/test/support/setup.js +54 -0
  41. package/READMEOLD.md +0 -1385
@@ -1,162 +1,48 @@
1
- # OIDC Methods Migration - Status Report
2
-
3
- ## 📋 Summary
4
-
5
- Ho creato una soluzione **pronta all'uso** per migrare i metodi OIDC da `keycloak-api-manager` a `keycloak-express-middleware`.
6
-
7
- ## ✅ What's Been Done
8
-
9
- ### 1. **Ready-to-Integrate File: `oidc-methods.js`**
10
- - ✅ 3 metodi pronti: `generateAuthorizationUrl()`, `login()`, `loginPKCE()`
11
- - ✅ Full JSDoc documentation
12
- - ✅ No external dependencies (only Node.js crypto)
13
- - ✅ Copy-paste ready into the middleware class
14
- - ✅ Tested and verified
15
-
16
- ### 2. **Comprehensive Test Suite: `test/oidc-methods.test.js`**
17
- - ✅ 21 test cases, all passing
18
- - ✅ Tests configuration, PKCE generation, token exchange
19
- - ✅ Error handling and edge cases covered
20
- - ✅ Mock fetch to avoid external calls
21
- - ✅ Run with: `npm test`
22
-
23
- ### 3. **Integration Guide: `OIDC_INTEGRATION_GUIDE.md`**
24
- - ✅ Step-by-step instructions
25
- - ✅ Copy-paste code snippets
26
- - ✅ Troubleshooting guide
27
- - ✅ Usage examples
28
- - ✅ Verification checklist
29
-
30
- ### 4. **Files Location (keycloak-express-middleware)**
31
- ```
32
- keycloak-express-middleware/
33
- ├── oidc-methods.js ← Copy methods from here
34
- ├── test/
35
- │ └── oidc-methods.test.js ← Tests (21 passing ✓)
36
- └── OIDC_INTEGRATION_GUIDE.md ← Integration instructions
37
- ```
38
-
39
- ## 🚀 Next Steps
40
-
41
- ### **Option 1: Manual Integration (Safe & Controlled)**
42
- Follow the `OIDC_INTEGRATION_GUIDE.md`:
43
- 1. Add 2 lines to constructor (save clientId, clientSecret)
44
- 2. Copy 3 methods from `oidc-methods.js` into the class
45
- 3. Run `npm test` to verify
46
- 4. Deploy
47
-
48
- ### **Option 2: I Can Automate It**
49
- If you want me to:
50
- 1. Integrate the methods directly into `index.js`
51
- 2. Run full test suite
52
- 3. Create release v6.1.0 with OIDC support
53
- 4. Push to git and npm
54
-
55
- Just let me know!
56
-
57
- ## 📊 Test Results
58
-
59
- ```
60
- ✔ generateAuthorizationUrl() - 10 tests passing
61
- ✓ Generates valid authorization URLs with all OAuth2 parameters
62
- ✓ PKCE pair generation (random, cryptographically secure)
63
- ✓ SHA256 code_challenge validation
64
- ✓ Custom scope and state support
65
- ✓ CamelCase parameter aliasing
66
- ✓ Error handling for missing parameters
67
-
68
- ✔ login() - 6 tests passing
69
- ✓ Auto-append clientId and clientSecret
70
- ✓ Token endpoint communication
71
- ✓ Success and error response handling
72
- ✓ Credential construction
73
-
74
- ✔ loginPKCE() - 5 tests passing
75
- ✓ Parameter validation (code, verifier, redirect_uri)
76
- ✓ CamelCase aliases support
77
- ✓ PKCE token exchange construction
78
- ✓ Delegation to login()
79
-
80
- Total: 21 passing (57ms)
81
- ```
82
-
83
- ## 🎯 Architecture Decision
84
-
85
- **Why move from keycloak-api-manager to keycloak-express-middleware?**
86
-
87
- | Aspect | API Manager | Express Middleware |
88
- |--------|------------|-------------------|
89
- | Purpose | Admin resource management | User application auth |
90
- | OAuth2 Context | ❌ Not needed | ✅ Natural fit |
91
- | Session/Cookies | ❌ Not part of it | ✅ Full support |
92
- | Express integration | ❌ No | ✅ Yes |
93
- | Dependencies | ✅ keycloak-admin-client | ✅ keycloak-connect |
94
-
95
- **Result:** OIDC methods belong in the middleware package.
96
-
97
- ## 📝 Git History
98
-
99
- ```
100
- keycloak-express-middleware/main
101
- ├── ef61793 Feat: add ready-to-integrate OIDC methods (generateAuthorizationUrl, login, loginPKCE) with comprehensive tests
102
- ├── [previous middleware commits...]
103
- ```
104
-
105
- ## ⚠️ Important Notes
106
-
107
- ### ✅ Backward Compatibility
108
- - No breaking changes planned
109
- - Existing middleware functionality untouched
110
- - New methods are additions only
111
-
112
- ### 🔐 Security Considerations
113
- - PKCE verifier stored server-side only (session)
114
- - State parameter for CSRF protection
115
- - Tokens in HttpOnly cookies recommended
116
- - Code uses Go crypto best practices
117
-
118
- ### 📦 Dependencies
119
- - No new npm packages needed
120
- - Uses Node.js 18+ global fetch
121
- - For Node 16-17: `npm install node-fetch`
122
-
123
- ## 🎬 What You Can Do Now
124
-
125
- ### Test Everything Works
126
- ```bash
127
- cd keycloak-express-middleware
128
- npm test # All 21 tests pass ✓
129
- ```
130
-
131
- ### Review the Code
132
- - Open `oidc-methods.js` - See the implementation
133
- - Open `test/oidc-methods.test.js` - See comprehensive tests
134
- - Open `OIDC_INTEGRATION_GUIDE.md` - Integration instructions
135
-
136
- ### Integrate When Ready
137
- Follow `OIDC_INTEGRATION_GUIDE.md` to add to `index.js` class
138
-
139
- ## 🔄 Next: keycloak-api-manager Updates
140
-
141
- Once integrated in middleware, we should:
142
-
143
- 1. **Deprecate in keycloak-api-manager v6.0.0**
144
- - Mark `auth()`, `login()`, `loginPKCE()` as deprecated
145
- - Update docs with migration guide
146
- - Keep methods working (backward compat)
147
-
148
- 2. **Update documentation**
149
- - Remove OIDC docs from API manager
150
- - Add migration guide to middleware
151
- - Update PKCE guide to use middleware
1
+ # OIDC Migration Status
152
2
 
153
- 3. **Release cycle**
154
- - keycloak-express-middleware v6.1.0 with OIDC support
155
- - keycloak-api-manager v6.0.0 with deprecation warnings
3
+ ## Summary
156
4
 
157
- ## 📞 Questions?
158
-
159
- All documentation is in:
160
- - `OIDC_INTEGRATION_GUIDE.md` - How to integrate
161
- - `oidc-methods.js` - Full JSDoc comments
162
- - `test/oidc-methods.test.js` - Real usage examples
5
+ OIDC runtime helpers are now documented and implemented in `keycloak-express-middleware`, with test coverage and integration guidance aligned to the current constructor-based API.
6
+
7
+ ## Implemented Scope
8
+
9
+ The following helper methods are part of the migration scope:
10
+
11
+ - `generateAuthorizationUrl(options)`
12
+ - `loginWithCredentials(credentials)`
13
+ - `loginPKCE(credentials)`
14
+
15
+ These methods are documented in:
16
+
17
+ - `docs/api/oidc-token-endpoint.md`
18
+ - `docs/OIDC_INTEGRATION_GUIDE.md`
19
+
20
+ ## Validation Status
21
+
22
+ - OIDC helper methods documented with parameters, return values, and examples
23
+ - Integration guide updated to reflect constructor-based initialization
24
+ - Naming consistency aligned with code (`keyCloackConfig`, `keyCloackOptions`)
25
+ - Error handling guidance included for common runtime failures
26
+
27
+ ## Design Rationale
28
+
29
+ OIDC login flow helpers belong in the Express middleware package because they are coupled to request/session lifecycle and application routing concerns.
30
+
31
+ | Aspect | keycloak-api-manager | keycloak-express-middleware |
32
+ |--------|----------------------|-----------------------------|
33
+ | Primary purpose | Admin API orchestration | Application authentication and authorization |
34
+ | Session/cookie awareness | No | Yes |
35
+ | Express routing integration | No | Yes |
36
+ | OIDC runtime flow fit | Limited | Native |
37
+
38
+ ## Compatibility Notes
39
+
40
+ - The migration is additive for middleware users.
41
+ - Existing middleware behavior remains unchanged.
42
+ - Runtime requirements remain compatible with Node.js 18+ (`fetch` available globally).
43
+
44
+ ## Recommended Next Steps
45
+
46
+ 1. Validate your local environment with `npm test`.
47
+ 2. Review `docs/OIDC_INTEGRATION_GUIDE.md` for implementation-level guidance.
48
+ 3. Use `docs/api-reference.md` as the canonical API entry point.
@@ -1,251 +1,23 @@
1
- # Integration Guide: Adding OIDC Methods to keycloak-express-middleware
1
+ # OIDC Integration Guide
2
2
 
3
- This guide explains how to integrate the new OIDC authentication methods (`generateAuthorizationUrl()`, `login()`, `loginPKCE()`) into the `keycloak-express-middleware` class.
3
+ This root-level guide is intentionally kept short to avoid drift.
4
+ The canonical and maintained version is:
4
5
 
5
- ## Files Created
6
+ - docs/OIDC_INTEGRATION_GUIDE.md
6
7
 
7
- - **`oidc-methods.js`** - Ready-to-use OIDC methods (no external dependencies)
8
- - **`test/oidc-methods.test.js`** - Complete test suite (run with `npm test`)
8
+ Current OIDC helper methods in code are:
9
9
 
10
- ## Integration Steps
10
+ - generateAuthorizationUrl(options)
11
+ - loginWithCredentials(credentials)
12
+ - loginPKCE(credentials)
11
13
 
12
- ### Step 1: Run Tests (Verify Methods Work)
14
+ Important alignment notes with current implementation:
13
15
 
14
- ```bash
15
- npm test
16
- ```
16
+ - Initialization is constructor-based, not configure-based.
17
+ - Use a middleware instance created with:
18
+ new keycloackAdapter(app, keyCloackConfig, keyCloackOptions)
19
+ - For generic token endpoint exchange use loginWithCredentials, not login.
17
20
 
18
- Expected output: All tests should pass (20+ assertions)
21
+ Quick verification command:
19
22
 
20
- ### Step 2: Locate the Constructor in index.js
21
-
22
- Find the `keycloakExpressMiddleware` constructor:
23
-
24
- ```javascript
25
- constructor(app, keyCloackConfig, keyCloackOptions) {
26
- this.keycloak = null;
27
- this.ready = false;
28
- this.readyQueue = [];
29
- this.realmName = keyCloackConfig.realm || keyCloackOptions.realmName;
30
- this.authServerUrl = keyCloackConfig['auth-server-url'];
31
- // ... rest of constructor
32
- }
33
- ```
34
-
35
- ### Step 3: Save Configuration in Constructor
36
-
37
- Add these lines after `this.authServerUrl`:
38
-
39
- ```javascript
40
- // Store OIDC configuration for token endpoint helpers
41
- this.clientId = keyCloackConfig.resource || keyCloackOptions.clientId;
42
- this.clientSecret = keyCloackConfig.credentials?.secret || keyCloackOptions.clientSecret;
43
- ```
44
-
45
- **Full example:**
46
-
47
- ```javascript
48
- constructor(app, keyCloackConfig, keyCloackOptions) {
49
- this.keycloak = null;
50
- this.ready = false;
51
- this.readyQueue = [];
52
- this.realmName = keyCloackConfig.realm || keyCloackOptions.realmName;
53
- this.authServerUrl = keyCloackConfig['auth-server-url'];
54
-
55
- // NEW: Store OIDC configuration
56
- this.clientId = keyCloackConfig.resource || keyCloackOptions.clientId;
57
- this.clientSecret = keyCloackConfig.credentials?.secret || keyCloackOptions.clientSecret;
58
-
59
- // ... rest of constructor (unchanged)
60
- }
61
- ```
62
-
63
- ### Step 4: Add Methods to the Class
64
-
65
- At the end of the `keycloakExpressMiddleware` class (before the closing brace), add these three methods from `oidc-methods.js`:
66
-
67
- ```javascript
68
- // ===== OIDC Authentication Methods =====
69
-
70
- /**
71
- * Generate Authorization URL + PKCE pair for OAuth2 flow
72
- * See oidc-methods.js for full documentation
73
- */
74
- generateAuthorizationUrl(options = {}) {
75
- // ... copy from oidc-methods.js
76
- }
77
-
78
- /**
79
- * Exchange credentials for OIDC tokens (generic token endpoint)
80
- * See oidc-methods.js for full documentation
81
- */
82
- async login(credentials = {}) {
83
- // ... copy from oidc-methods.js
84
- }
85
-
86
- /**
87
- * Exchange authorization code + PKCE verifier for tokens
88
- * See oidc-methods.js for full documentation
89
- */
90
- async loginPKCE(credentials = {}) {
91
- // ... copy from oidc-methods.js
92
- }
93
- ```
94
-
95
- **Option: Copy-Paste from oidc-methods.js**
96
-
97
- You can copy the entire content from `oidc-methods.js` (lines with the three functions) directly into the class.
98
-
99
- ### Step 5: Run Tests Again
100
-
101
- ```bash
102
- npm test
103
- ```
104
-
105
- Verify that all tests pass with the new methods integrated.
106
-
107
- ### Step 6: Test in Your Application
108
-
109
- Create a simple test to verify the middleware works:
110
-
111
- ```javascript
112
- const keycloakAdapter = require('keycloak-express-middleware');
113
- const express = require('express');
114
-
115
- const app = express();
116
-
117
- // Configure middleware
118
- await keycloakAdapter.configure({
119
- app,
120
- keyCloakConfig: {
121
- realm: 'my-realm',
122
- 'auth-server-url': 'https://keycloak.example.com/',
123
- resource: 'my-client',
124
- credentials: { secret: 'my-secret' }
125
- }
126
- });
127
-
128
- // Test PKCE flow initialization
129
- const pkceFlow = keycloakAdapter.generateAuthorizationUrl({
130
- redirect_uri: 'http://localhost:3000/auth/callback'
131
- });
132
-
133
- console.log('Auth URL:', pkceFlow.authUrl);
134
- console.log('State:', pkceFlow.state);
135
- console.log('Code Verifier:', pkceFlow.codeVerifier);
136
- ```
137
-
138
- ## Key Points
139
-
140
- ### 1. No External Dependencies
141
- - Uses only Node.js built-in `crypto` module
142
- - Uses global `fetch` (available in Node 18+)
143
- - No new npm packages needed
144
-
145
- ### 2. Backward Compatibility
146
- - All existing middleware functionality remains unchanged
147
- - New methods are optional additions
148
- - No breaking changes to existing API
149
-
150
- ### 3. Configuration Sources
151
- The three methods use these configuration values from the middleware:
152
- - `this.authServerUrl` - From `keyCloakConfig['auth-server-url']`
153
- - `this.realmName` - From `keyCloakConfig.realm`
154
- - `this.clientId` - From `keyCloakConfig.resource` (or `keyCloackOptions.clientId`)
155
- - `this.clientSecret` - From `keyCloakConfig.credentials.secret` (or `keyCloackOptions.clientSecret`)
156
-
157
- ### 4. Usage Examples
158
-
159
- #### Generate Authorization URL (for PKCE login initiation)
160
-
161
- ```javascript
162
- const pkceFlow = keycloakAdapter.generateAuthorizationUrl({
163
- redirect_uri: 'https://app.example.com/auth/callback',
164
- scope: 'openid profile email' // optional
165
- });
166
-
167
- req.session.pkce_state = pkceFlow.state;
168
- req.session.pkce_verifier = pkceFlow.codeVerifier;
169
-
170
- res.redirect(pkceFlow.authUrl);
171
- ```
172
-
173
- #### Exchange Code for Token (for PKCE callback)
174
-
175
- ```javascript
176
- const tokens = await keycloakAdapter.loginPKCE({
177
- code: req.query.code,
178
- redirect_uri: 'https://app.example.com/auth/callback',
179
- code_verifier: req.session.pkce_verifier
180
- });
181
-
182
- res.cookie('access_token', tokens.access_token, { httpOnly: true });
183
- res.redirect('/dashboard');
184
- ```
185
-
186
- #### Direct Token Grant
187
-
188
- ```javascript
189
- // Password grant
190
- const tokens = await keycloakAdapter.login({
191
- grant_type: 'password',
192
- username: 'user@example.com',
193
- password: 'password123'
194
- });
195
-
196
- // Client credentials
197
- const tokens = await keycloakAdapter.login({
198
- grant_type: 'client_credentials'
199
- });
200
-
201
- // Refresh token
202
- const newTokens = await keycloakAdapter.login({
203
- grant_type: 'refresh_token',
204
- refresh_token: oldRefreshToken
205
- });
206
- ```
207
-
208
- ## Verification Checklist
209
-
210
- - [ ] All tests in `test/oidc-methods.test.js` pass
211
- - [ ] Constructor saves `clientId` and `clientSecret`
212
- - [ ] Three methods added to the class
213
- - [ ] `generateAuthorizationUrl()` works
214
- - [ ] `login()` works
215
- - [ ] `loginPKCE()` works
216
- - [ ] Existing middleware functionality still works
217
- - [ ] No runtime errors
218
-
219
- ## Troubleshooting
220
-
221
- ### Error: "requires middleware to be initialized"
222
- - Ensure `configure()` was called before using OIDC methods
223
- - Verify `authServerUrl`, `realmName`, and `clientId` are set
224
-
225
- ### Error: "generateAuthorizationUrl requires redirect_uri"
226
- - Pass `redirect_uri` or `redirectUri` in options object
227
-
228
- ### Fetch errors
229
- - Ensure Node.js 18+ (for global fetch)
230
- - For Node 16-17, add: `npm install node-fetch`
231
-
232
- ## Testing Checklist
233
-
234
- Run tests to verify:
235
-
236
- ```bash
237
- # All tests pass
238
- npm test
239
-
240
- # Test output shows:
241
- # - 20+ assertions passing
242
- # - No failures
243
- # - OIDC Methods suite: ✓
244
- ```
245
-
246
- ## Questions?
247
-
248
- Refer to:
249
- - `oidc-methods.js` - Method implementations and full JSDoc documentation
250
- - `test/oidc-methods.test.js` - Test examples showing all use cases
251
- - [PKCE Login Flow Guide](../keycloak-api-manager/docs/guides/PKCE-Login-Flow.md) - Real-world usage patterns
23
+ - npm test