0
# Session Management
1
2
The session management system in Keycloak SPI provides centralized access to all providers and services through the KeycloakSession interface. It also manages transactions, context information, and provider lifecycle.
3
4
## Core Session Interfaces
5
6
### KeycloakSession
7
8
The main session interface providing access to providers and transaction management.
9
10
```java { .api }
11
public interface KeycloakSession extends AutoCloseable {
12
/**
13
* Gets the current request context information.
14
*
15
* @return the context
16
*/
17
KeycloakContext getContext();
18
19
/**
20
* Gets the transaction manager for this session.
21
*
22
* @return the transaction manager
23
*/
24
KeycloakTransactionManager getTransactionManager();
25
26
/**
27
* Gets a provider instance for the specified provider class.
28
* Uses the default provider implementation.
29
*
30
* @param clazz the provider class
31
* @return provider instance
32
*/
33
<T extends Provider> T getProvider(Class<T> clazz);
34
35
/**
36
* Gets a provider instance for the specified provider class and ID.
37
*
38
* @param clazz the provider class
39
* @param id the provider ID
40
* @return provider instance
41
*/
42
<T extends Provider> T getProvider(Class<T> clazz, String id);
43
44
/**
45
* Gets all provider instances for the specified provider class.
46
*
47
* @param clazz the provider class
48
* @return set of provider instances
49
*/
50
<T extends Provider> Set<T> getAllProviders(Class<T> clazz);
51
52
/**
53
* Gets the realm provider for realm operations.
54
*
55
* @return realm provider
56
*/
57
RealmProvider realms();
58
59
/**
60
* Gets the user provider for user operations.
61
*
62
* @return user provider
63
*/
64
UserProvider users();
65
66
/**
67
* Gets the client provider for client operations.
68
*
69
* @return client provider
70
*/
71
ClientProvider clients();
72
73
/**
74
* Gets the client scope provider for client scope operations.
75
*
76
* @return client scope provider
77
*/
78
ClientScopeProvider clientScopes();
79
80
/**
81
* Gets the group provider for group operations.
82
*
83
* @return group provider
84
*/
85
GroupProvider groups();
86
87
/**
88
* Gets the role provider for role operations.
89
*
90
* @return role provider
91
*/
92
RoleProvider roles();
93
94
/**
95
* Gets the user session provider for session operations.
96
*
97
* @return user session provider
98
*/
99
UserSessionProvider sessions();
100
101
/**
102
* Gets the authentication session provider.
103
*
104
* @return authentication session provider
105
*/
106
AuthenticationSessionProvider authenticationSessions();
107
108
/**
109
* Gets the user login failure provider.
110
*
111
* @return user login failure provider
112
*/
113
UserLoginFailureProvider loginFailures();
114
115
/**
116
* Gets the single use object provider.
117
*
118
* @return single use object provider
119
*/
120
SingleUseObjectProvider singleUseObjects();
121
122
/**
123
* Gets a named attribute from the session.
124
*
125
* @param attribute the attribute name
126
* @return attribute value
127
*/
128
Object getAttribute(String attribute);
129
130
/**
131
* Sets a named attribute in the session.
132
*
133
* @param name the attribute name
134
* @param value the attribute value
135
* @return previous value
136
*/
137
Object setAttribute(String name, Object value);
138
139
/**
140
* Removes a named attribute from the session.
141
*
142
* @param name the attribute name
143
* @return removed value
144
*/
145
Object removeAttribute(String name);
146
147
/**
148
* Gets the key manager for cryptographic operations.
149
*
150
* @return key manager
151
*/
152
KeyManager keys();
153
154
/**
155
* Gets the theme manager for theme operations.
156
*
157
* @return theme manager
158
*/
159
ThemeManager theme();
160
161
/**
162
* Gets the token manager for token operations.
163
*
164
* @return token manager
165
*/
166
TokenManager tokens();
167
168
/**
169
* Gets the vault transcriber for secret resolution.
170
*
171
* @return vault transcriber
172
*/
173
VaultTranscriber vault();
174
175
/**
176
* Gets the client policy manager.
177
*
178
* @return client policy manager
179
*/
180
ClientPolicyManager clientPolicy();
181
182
/**
183
* Invalidates cached objects of the specified type.
184
*
185
* @param type the object type to invalidate
186
* @param params invalidation parameters
187
*/
188
void invalidate(InvalidableObjectType type, Object... params);
189
}
190
```
191
192
### KeycloakSessionFactory
193
194
Factory for creating KeycloakSession instances.
195
196
```java { .api }
197
public interface KeycloakSessionFactory extends AutoCloseable {
198
/**
199
* Creates a new Keycloak session.
200
*
201
* @return new session instance
202
*/
203
KeycloakSession create();
204
205
/**
206
* Creates a new Keycloak session for the specified realm.
207
*
208
* @param realmModel the realm
209
* @return new session instance
210
*/
211
KeycloakSession create(RealmModel realmModel);
212
213
/**
214
* Publishes an event to all event listeners.
215
*
216
* @param event the event to publish
217
*/
218
void publish(ProviderEvent event);
219
220
/**
221
* Registers an event listener.
222
*
223
* @param listener the event listener
224
*/
225
void register(ProviderEventListener listener);
226
227
/**
228
* Unregisters an event listener.
229
*
230
* @param listener the event listener
231
*/
232
void unregister(ProviderEventListener listener);
233
234
/**
235
* Gets the provider event manager.
236
*
237
* @return event manager
238
*/
239
ProviderEventManager getProviderEventManager();
240
}
241
```
242
243
### KeycloakContext
244
245
Provides access to request context information.
246
247
```java { .api }
248
public interface KeycloakContext {
249
/**
250
* Gets the auth server URL.
251
*
252
* @return auth server URL
253
*/
254
URI getAuthServerUrl();
255
256
/**
257
* Gets the context path.
258
*
259
* @return context path
260
*/
261
String getContextPath();
262
263
/**
264
* Gets the URI information for the current request.
265
*
266
* @return URI info
267
*/
268
UriInfo getUri();
269
270
/**
271
* Gets the HTTP headers for the current request.
272
*
273
* @return HTTP headers
274
*/
275
HttpHeaders getRequestHeaders();
276
277
/**
278
* Gets the current realm.
279
*
280
* @return current realm or null
281
*/
282
RealmModel getRealm();
283
284
/**
285
* Sets the current realm.
286
*
287
* @param realm the realm to set
288
*/
289
void setRealm(RealmModel realm);
290
291
/**
292
* Gets the current client.
293
*
294
* @return current client or null
295
*/
296
ClientModel getClient();
297
298
/**
299
* Sets the current client.
300
*
301
* @param client the client to set
302
*/
303
void setClient(ClientModel client);
304
305
/**
306
* Gets the connection information.
307
*
308
* @return connection info
309
*/
310
ClientConnection getConnection();
311
312
/**
313
* Gets the Keycloak URI information.
314
*
315
* @return Keycloak URI info
316
*/
317
KeycloakUriInfo getUriInfo();
318
319
/**
320
* Gets the HTTP request.
321
*
322
* @return HTTP request
323
*/
324
HttpRequest getHttpRequest();
325
326
/**
327
* Gets the HTTP response.
328
*
329
* @return HTTP response
330
*/
331
HttpResponse getHttpResponse();
332
}
333
```
334
335
## Transaction Management
336
337
### KeycloakTransaction
338
339
Base interface for transactions.
340
341
```java { .api }
342
public interface KeycloakTransaction {
343
/**
344
* Begins the transaction.
345
*/
346
void begin();
347
348
/**
349
* Commits the transaction.
350
*/
351
void commit();
352
353
/**
354
* Rolls back the transaction.
355
*/
356
void rollback();
357
358
/**
359
* Sets rollback only flag.
360
*/
361
void setRollbackOnly();
362
363
/**
364
* Checks if transaction is marked for rollback only.
365
*
366
* @return true if rollback only
367
*/
368
boolean getRollbackOnly();
369
370
/**
371
* Checks if transaction is active.
372
*
373
* @return true if active
374
*/
375
boolean isActive();
376
}
377
```
378
379
### KeycloakTransactionManager
380
381
Manages transactions for the session.
382
383
```java { .api }
384
public interface KeycloakTransactionManager extends KeycloakTransaction {
385
/**
386
* Enlists a transaction participant.
387
*
388
* @param transaction the transaction to enlist
389
*/
390
void enlist(KeycloakTransaction transaction);
391
392
/**
393
* Enlists a transaction after completion callback.
394
*
395
* @param afterCompletion the callback
396
*/
397
void enlistAfterCompletion(KeycloakTransaction afterCompletion);
398
399
/**
400
* Enlists a transaction before completion callback.
401
*
402
* @param beforeCompletion the callback
403
*/
404
void enlistBeforeCompletion(KeycloakTransaction beforeCompletion);
405
406
/**
407
* Enlists a transaction prepared callback.
408
*
409
* @param prepared the callback
410
*/
411
void enlistPrepare(KeycloakTransaction prepared);
412
}
413
```
414
415
### AbstractKeycloakTransaction
416
417
Abstract base class for transaction implementations.
418
419
```java { .api }
420
public abstract class AbstractKeycloakTransaction implements KeycloakTransaction {
421
private boolean started = false;
422
private boolean rollbackOnly = false;
423
424
@Override
425
public void begin() {
426
started = true;
427
}
428
429
@Override
430
public void commit() {
431
if (getRollbackOnly()) {
432
rollback();
433
return;
434
}
435
if (started) {
436
commitImpl();
437
}
438
}
439
440
@Override
441
public void rollback() {
442
if (started) {
443
rollbackImpl();
444
}
445
}
446
447
@Override
448
public void setRollbackOnly() {
449
rollbackOnly = true;
450
}
451
452
@Override
453
public boolean getRollbackOnly() {
454
return rollbackOnly;
455
}
456
457
@Override
458
public boolean isActive() {
459
return started;
460
}
461
462
/**
463
* Implement actual commit logic.
464
*/
465
protected abstract void commitImpl();
466
467
/**
468
* Implement actual rollback logic.
469
*/
470
protected abstract void rollbackImpl();
471
}
472
```
473
474
## Session Tasks
475
476
### KeycloakSessionTask
477
478
Interface for tasks that need a Keycloak session.
479
480
```java { .api }
481
public interface KeycloakSessionTask {
482
/**
483
* Runs the task with the provided session.
484
*
485
* @param session the Keycloak session
486
*/
487
void run(KeycloakSession session);
488
}
489
```
490
491
### KeycloakSessionTaskWithResult
492
493
Interface for tasks that return a result.
494
495
```java { .api }
496
public interface KeycloakSessionTaskWithResult<V> {
497
/**
498
* Runs the task with the provided session and returns a result.
499
*
500
* @param session the Keycloak session
501
* @return task result
502
*/
503
V run(KeycloakSession session);
504
}
505
```
506
507
## Usage Examples
508
509
### Basic Session Usage
510
511
```java
512
// Create and use a session
513
try (KeycloakSession session = sessionFactory.create()) {
514
// Get providers
515
RealmProvider realms = session.realms();
516
UserProvider users = session.users();
517
518
// Get specific realm
519
RealmModel realm = realms.getRealmByName("myrealm");
520
session.getContext().setRealm(realm);
521
522
// Work with users
523
UserModel user = users.getUserByUsername(realm, "john");
524
if (user != null) {
525
user.setEmail("john@example.com");
526
}
527
528
// Transaction is automatically committed when session closes
529
}
530
```
531
532
### Transaction Management
533
534
```java
535
try (KeycloakSession session = sessionFactory.create()) {
536
KeycloakTransactionManager transaction = session.getTransactionManager();
537
538
// Begin transaction explicitly
539
transaction.begin();
540
541
try {
542
// Perform operations
543
RealmModel realm = session.realms().getRealmByName("myrealm");
544
UserModel user = session.users().addUser(realm, "newuser");
545
user.setEmail("newuser@example.com");
546
547
// Custom transaction participant
548
transaction.enlist(new KeycloakTransaction() {
549
@Override
550
public void begin() {}
551
552
@Override
553
public void commit() {
554
// Custom commit logic (e.g., send email)
555
sendWelcomeEmail(user);
556
}
557
558
@Override
559
public void rollback() {
560
// Custom rollback logic
561
}
562
563
@Override
564
public void setRollbackOnly() {}
565
566
@Override
567
public boolean getRollbackOnly() { return false; }
568
569
@Override
570
public boolean isActive() { return true; }
571
});
572
573
// Commit transaction
574
transaction.commit();
575
576
} catch (Exception e) {
577
transaction.rollback();
578
throw e;
579
}
580
}
581
```
582
583
### Using Session Tasks
584
585
```java
586
// Execute a task with automatic session management
587
sessionFactory.runInTransaction(session -> {
588
RealmModel realm = session.realms().getRealmByName("myrealm");
589
UserModel user = session.users().getUserByUsername(realm, "john");
590
if (user != null) {
591
user.setEnabled(false);
592
}
593
});
594
595
// Execute a task that returns a result
596
String result = sessionFactory.runInTransaction(session -> {
597
RealmModel realm = session.realms().getRealmByName("myrealm");
598
return realm.getDisplayName();
599
});
600
```
601
602
### Provider Access Patterns
603
604
```java
605
try (KeycloakSession session = sessionFactory.create()) {
606
// Get default provider
607
UserStorageProvider userStorage = session.getProvider(UserStorageProvider.class);
608
609
// Get specific provider implementation
610
UserStorageProvider ldapProvider = session.getProvider(UserStorageProvider.class, "ldap");
611
612
// Get all provider implementations
613
Set<UserStorageProvider> allProviders = session.getAllProviders(UserStorageProvider.class);
614
615
// Access built-in providers
616
RealmProvider realms = session.realms();
617
UserProvider users = session.users();
618
ClientProvider clients = session.clients();
619
}
620
```
621
622
### Context Information
623
624
```java
625
try (KeycloakSession session = sessionFactory.create()) {
626
KeycloakContext context = session.getContext();
627
628
// Get request information
629
UriInfo uriInfo = context.getUri();
630
HttpHeaders headers = context.getRequestHeaders();
631
String userAgent = headers.getHeaderString("User-Agent");
632
633
// Get/set current realm and client
634
RealmModel realm = context.getRealm();
635
ClientModel client = context.getClient();
636
637
// Access connection info
638
ClientConnection connection = context.getConnection();
639
String remoteAddr = connection.getRemoteAddr();
640
String remoteHost = connection.getRemoteHost();
641
}
642
```
643
644
### Session Attributes
645
646
```java
647
try (KeycloakSession session = sessionFactory.create()) {
648
// Store data in session
649
session.setAttribute("myKey", "myValue");
650
651
// Retrieve data from session
652
String value = (String) session.getAttribute("myKey");
653
654
// Remove data from session
655
Object removed = session.removeAttribute("myKey");
656
}
657
```