keycloak-express-middleware 6.1.1 → 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.
@@ -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,248 +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
- ```
134
-
135
- ## Key Points
136
-
137
- ### 1. No External Dependencies
138
- - Uses only Node.js built-in `crypto` module
139
- - Uses global `fetch` (available in Node 18+)
140
- - No new npm packages needed
141
-
142
- ### 2. Backward Compatibility
143
- - All existing middleware functionality remains unchanged
144
- - New methods are optional additions
145
- - No breaking changes to existing API
146
-
147
- ### 3. Configuration Sources
148
- The three methods use these configuration values from the middleware:
149
- - `this.authServerUrl` - From `keyCloakConfig['auth-server-url']`
150
- - `this.realmName` - From `keyCloakConfig.realm`
151
- - `this.clientId` - From `keyCloakConfig.resource` (or `keyCloackOptions.clientId`)
152
- - `this.clientSecret` - From `keyCloakConfig.credentials.secret` (or `keyCloackOptions.clientSecret`)
153
-
154
- ### 4. Usage Examples
155
-
156
- #### Generate Authorization URL (for PKCE login initiation)
157
-
158
- ```javascript
159
- const pkceFlow = keycloakAdapter.generateAuthorizationUrl({
160
- redirect_uri: 'https://app.example.com/auth/callback',
161
- scope: 'openid profile email' // optional
162
- });
163
-
164
- req.session.pkce_state = pkceFlow.state;
165
- req.session.pkce_verifier = pkceFlow.codeVerifier;
166
-
167
- res.redirect(pkceFlow.authUrl);
168
- ```
169
-
170
- #### Exchange Code for Token (for PKCE callback)
171
-
172
- ```javascript
173
- const tokens = await keycloakAdapter.loginPKCE({
174
- code: req.query.code,
175
- redirect_uri: 'https://app.example.com/auth/callback',
176
- code_verifier: req.session.pkce_verifier
177
- });
178
-
179
- res.cookie('access_token', tokens.access_token, { httpOnly: true });
180
- res.redirect('/dashboard');
181
- ```
182
-
183
- #### Direct Token Grant
184
-
185
- ```javascript
186
- // Password grant
187
- const tokens = await keycloakAdapter.login({
188
- grant_type: 'password',
189
- username: 'user@example.com',
190
- password: 'password123'
191
- });
192
-
193
- // Client credentials
194
- const tokens = await keycloakAdapter.login({
195
- grant_type: 'client_credentials'
196
- });
197
-
198
- // Refresh token
199
- const newTokens = await keycloakAdapter.login({
200
- grant_type: 'refresh_token',
201
- refresh_token: oldRefreshToken
202
- });
203
- ```
204
-
205
- ## Verification Checklist
206
-
207
- - [ ] All tests in `test/oidc-methods.test.js` pass
208
- - [ ] Constructor saves `clientId` and `clientSecret`
209
- - [ ] Three methods added to the class
210
- - [ ] `generateAuthorizationUrl()` works
211
- - [ ] `login()` works
212
- - [ ] `loginPKCE()` works
213
- - [ ] Existing middleware functionality still works
214
- - [ ] No runtime errors
215
-
216
- ## Troubleshooting
217
-
218
- ### Error: "requires middleware to be initialized"
219
- - Ensure `configure()` was called before using OIDC methods
220
- - Verify `authServerUrl`, `realmName`, and `clientId` are set
221
-
222
- ### Error: "generateAuthorizationUrl requires redirect_uri"
223
- - Pass `redirect_uri` or `redirectUri` in options object
224
-
225
- ### Fetch errors
226
- - Ensure Node.js 18+ (for global fetch)
227
- - For Node 16-17, add: `npm install node-fetch`
228
-
229
- ## Testing Checklist
230
-
231
- Run tests to verify:
232
-
233
- ```bash
234
- # All tests pass
235
- npm test
236
-
237
- # Test output shows:
238
- # - 20+ assertions passing
239
- # - No failures
240
- # - OIDC Methods suite: ✓
241
- ```
242
-
243
- ## Questions?
244
-
245
- Refer to:
246
- - `oidc-methods.js` - Method implementations and full JSDoc documentation
247
- - `test/oidc-methods.test.js` - Test examples showing all use cases
248
- - [PKCE Login Flow Guide](../keycloak-api-manager/docs/guides/PKCE-Login-Flow.md) - Real-world usage patterns
23
+ - npm test