docs
0
# Realm Management
1
2
Realm configuration, import/export, event management, default groups, and administrative settings.
3
4
## Capabilities
5
6
### Realm CRUD Operations
7
8
Basic realm lifecycle management operations.
9
10
```typescript { .api }
11
/**
12
* Find all realms or search with criteria
13
* @param query - Optional search criteria
14
* @returns Array of realm representations
15
*/
16
find(query?: { briefRepresentation?: boolean }): Promise<RealmRepresentation[]>;
17
18
/**
19
* Create a new realm
20
* @param realm - Realm configuration
21
* @returns Object with created realm name
22
*/
23
create(realm: RealmRepresentation): Promise<{ realmName: string }>;
24
25
/**
26
* Find a specific realm by name
27
* @param params - Realm identifier
28
* @returns Realm representation or undefined if not found
29
*/
30
findOne(params: { realm: string }): Promise<RealmRepresentation | undefined>;
31
32
/**
33
* Update an existing realm configuration
34
* @param query - Realm identifier
35
* @param realm - Updated realm configuration
36
*/
37
update(query: { realm: string }, realm: RealmRepresentation): Promise<void>;
38
39
/**
40
* Delete a realm
41
* @param params - Realm identifier
42
*/
43
del(params: { realm: string }): Promise<void>;
44
```
45
46
**Usage Examples:**
47
48
```typescript
49
// List all realms
50
const realms = await kcAdminClient.realms.find();
51
console.log("Available realms:", realms.map(r => r.realm));
52
53
// Get brief representation only
54
const realmsBrief = await kcAdminClient.realms.find({
55
briefRepresentation: true,
56
});
57
58
// Create new realm
59
await kcAdminClient.realms.create({
60
realm: "my-app-realm",
61
displayName: "My Application Realm",
62
enabled: true,
63
sslRequired: "external",
64
registrationAllowed: true,
65
loginWithEmailAllowed: true,
66
duplicateEmailsAllowed: false,
67
resetPasswordAllowed: true,
68
editUsernameAllowed: false,
69
bruteForceProtected: true,
70
});
71
72
// Get specific realm
73
const realm = await kcAdminClient.realms.findOne({ realm: "my-app-realm" });
74
console.log("Realm settings:", realm);
75
76
// Update realm settings
77
await kcAdminClient.realms.update(
78
{ realm: "my-app-realm" },
79
{
80
displayName: "My Updated Application Realm",
81
registrationAllowed: false,
82
bruteForceProtected: true,
83
}
84
);
85
86
// Delete realm (careful!)
87
await kcAdminClient.realms.del({ realm: "test-realm" });
88
```
89
90
### Import and Export
91
92
Realm import/export functionality for configuration management and migrations.
93
94
```typescript { .api }
95
/**
96
* Partial import of realm configuration
97
* @param params - Realm and import configuration
98
* @returns Import results with conflicts and imported resources
99
*/
100
partialImport(params: {
101
realm: string;
102
rep: PartialImportRealmRepresentation;
103
}): Promise<PartialImportResponse>;
104
105
/**
106
* Export realm configuration
107
* @param params - Export options
108
* @returns Complete realm representation for export
109
*/
110
export(params: {
111
realm: string;
112
exportClients?: boolean;
113
exportGroupsAndRoles?: boolean;
114
}): Promise<RealmRepresentation>;
115
116
/**
117
* Partial import request configuration
118
*/
119
interface PartialImportRealmRepresentation {
120
/** Import policy for conflicts */
121
ifResourceExists?: "FAIL" | "SKIP" | "OVERWRITE";
122
/** Users to import */
123
users?: UserRepresentation[];
124
/** Clients to import */
125
clients?: ClientRepresentation[];
126
/** Groups to import */
127
groups?: GroupRepresentation[];
128
/** Roles to import */
129
roles?: {
130
realm?: RoleRepresentation[];
131
client?: Record<string, RoleRepresentation[]>;
132
};
133
/** Identity providers to import */
134
identityProviders?: IdentityProviderRepresentation[];
135
}
136
137
/**
138
* Results from partial import operation
139
*/
140
interface PartialImportResponse {
141
/** Number of resources imported */
142
imported: number;
143
/** Number of resources skipped */
144
skipped: number;
145
/** Import results by resource type */
146
results: {
147
users?: number;
148
clients?: number;
149
groups?: number;
150
roles?: number;
151
identityProviders?: number;
152
};
153
}
154
```
155
156
**Usage Examples:**
157
158
```typescript
159
// Export realm configuration
160
const realmExport = await kcAdminClient.realms.export({
161
realm: "my-app-realm",
162
exportClients: true,
163
exportGroupsAndRoles: true,
164
});
165
166
// Save to file or transfer to another environment
167
console.log("Exported realm config:", JSON.stringify(realmExport, null, 2));
168
169
// Partial import with overwrite policy
170
const importResult = await kcAdminClient.realms.partialImport({
171
realm: "target-realm",
172
rep: {
173
ifResourceExists: "OVERWRITE",
174
users: [
175
{
176
username: "imported-user",
177
email: "user@example.com",
178
enabled: true,
179
},
180
],
181
clients: [
182
{
183
clientId: "imported-client",
184
enabled: true,
185
publicClient: false,
186
},
187
],
188
roles: {
189
realm: [
190
{
191
name: "imported-role",
192
description: "Role imported from another realm",
193
},
194
],
195
},
196
},
197
});
198
199
console.log(`Import completed: ${importResult.imported} imported, ${importResult.skipped} skipped`);
200
```
201
202
### Default Groups
203
204
Management of realm-level default group assignments.
205
206
```typescript { .api }
207
/**
208
* Get default groups for the realm
209
* @param params - Realm identifier
210
* @returns Array of default groups
211
*/
212
getDefaultGroups(params: { realm: string }): Promise<GroupRepresentation[]>;
213
214
/**
215
* Add a group to realm default groups
216
* @param params - Realm and group identifiers
217
*/
218
addDefaultGroup(params: { realm: string; id: string }): Promise<void>;
219
220
/**
221
* Remove a group from realm default groups
222
* @param params - Realm and group identifiers
223
*/
224
removeDefaultGroup(params: { realm: string; id: string }): Promise<void>;
225
```
226
227
**Usage Examples:**
228
229
```typescript
230
// Get current default groups
231
const defaultGroups = await kcAdminClient.realms.getDefaultGroups({
232
realm: "my-app-realm",
233
});
234
console.log("Default groups:", defaultGroups.map(g => g.name));
235
236
// Add group to defaults (new users will automatically join)
237
await kcAdminClient.realms.addDefaultGroup({
238
realm: "my-app-realm",
239
id: "group-uuid-here",
240
});
241
242
// Remove group from defaults
243
await kcAdminClient.realms.removeDefaultGroup({
244
realm: "my-app-realm",
245
id: "group-uuid-here",
246
});
247
```
248
249
### Event Management
250
251
Configuration and retrieval of audit events and admin events.
252
253
```typescript { .api }
254
/**
255
* Find user events with optional filtering
256
* @param params - Realm and event query parameters
257
* @returns Array of user events
258
*/
259
findEvents(params: { realm: string } & EventQuery): Promise<EventRepresentation[]>;
260
261
/**
262
* Get realm events configuration
263
* @param params - Realm identifier
264
* @returns Current events configuration
265
*/
266
getEventsConfig(params: { realm: string }): Promise<RealmEventsConfigRepresentation>;
267
268
/**
269
* Update realm events configuration
270
* @param query - Realm identifier
271
* @param config - New events configuration
272
*/
273
updateEventsConfig(
274
query: { realm: string },
275
config: RealmEventsConfigRepresentation
276
): Promise<void>;
277
278
/**
279
* Find admin events with optional filtering
280
* @param params - Realm and admin event query parameters
281
* @returns Array of admin events
282
*/
283
findAdminEvents(params: { realm: string } & AdminEventQuery): Promise<AdminEventRepresentation[]>;
284
285
/**
286
* Event query parameters for filtering user events
287
*/
288
interface EventQuery {
289
/** Event types to include */
290
type?: string[];
291
/** Client ID filter */
292
client?: string;
293
/** User ID filter */
294
user?: string;
295
/** Date range start */
296
dateFrom?: string;
297
/** Date range end */
298
dateTo?: string;
299
/** IP address filter */
300
ipAddress?: string;
301
/** Maximum number of events to return */
302
max?: number;
303
/** Number of events to skip */
304
first?: number;
305
}
306
307
/**
308
* Admin event query parameters
309
*/
310
interface AdminEventQuery {
311
/** Operation types to include */
312
operationTypes?: string[];
313
/** Authentication realm filter */
314
authRealm?: string;
315
/** Authentication client filter */
316
authClient?: string;
317
/** Authentication user filter */
318
authUser?: string;
319
/** Authentication IP address filter */
320
authIpAddress?: string;
321
/** Resource path filter */
322
resourcePath?: string;
323
/** Date range start */
324
dateFrom?: string;
325
/** Date range end */
326
dateTo?: string;
327
/** Maximum number of events to return */
328
max?: number;
329
/** Number of events to skip */
330
first?: number;
331
}
332
```
333
334
**Usage Examples:**
335
336
```typescript
337
// Get recent login events
338
const loginEvents = await kcAdminClient.realms.findEvents({
339
realm: "my-app-realm",
340
type: ["LOGIN", "LOGIN_ERROR"],
341
dateFrom: "2023-01-01",
342
max: 100,
343
});
344
345
console.log("Recent login attempts:", loginEvents.length);
346
347
// Get admin events
348
const adminEvents = await kcAdminClient.realms.findAdminEvents({
349
realm: "my-app-realm",
350
operationTypes: ["CREATE", "UPDATE", "DELETE"],
351
authUser: "admin",
352
max: 50,
353
});
354
355
// Configure event logging
356
await kcAdminClient.realms.updateEventsConfig(
357
{ realm: "my-app-realm" },
358
{
359
eventsEnabled: true,
360
eventsExpiration: 2592000, // 30 days
361
eventsListeners: ["jboss-logging"],
362
enabledEventTypes: [
363
"LOGIN",
364
"LOGIN_ERROR",
365
"REGISTER",
366
"LOGOUT",
367
"CLIENT_LOGIN",
368
],
369
adminEventsEnabled: true,
370
adminEventsDetailsEnabled: true,
371
}
372
);
373
```
374
375
### Keys and Certificates
376
377
Realm cryptographic key management.
378
379
```typescript { .api }
380
/**
381
* Get realm's cryptographic keys and certificates
382
* @param params - Realm identifier
383
* @returns Keys metadata including public keys and certificates
384
*/
385
getKeys(params: { realm: string }): Promise<KeysMetadataRepresentation>;
386
387
/**
388
* Cryptographic keys metadata
389
*/
390
interface KeysMetadataRepresentation {
391
/** Active keys */
392
keys?: KeyMetadataRepresentation[];
393
/** Available key algorithms */
394
algorithms?: string[];
395
}
396
397
/**
398
* Individual key metadata
399
*/
400
interface KeyMetadataRepresentation {
401
/** Key provider ID */
402
providerId?: string;
403
/** Provider priority */
404
providerPriority?: number;
405
/** Key ID */
406
kid?: string;
407
/** Key status */
408
status?: "ACTIVE" | "PASSIVE" | "DISABLED";
409
/** Key type */
410
type?: string;
411
/** Key algorithm */
412
algorithm?: string;
413
/** Public key */
414
publicKey?: string;
415
/** X.509 certificate */
416
certificate?: string;
417
}
418
```
419
420
**Usage Examples:**
421
422
```typescript
423
// Get realm keys
424
const keys = await kcAdminClient.realms.getKeys({ realm: "my-app-realm" });
425
426
console.log("Available algorithms:", keys.algorithms);
427
console.log("Active keys:", keys.keys?.filter(k => k.status === "ACTIVE"));
428
429
// Find RSA signing keys
430
const rsaKeys = keys.keys?.filter(k =>
431
k.algorithm === "RS256" && k.type === "RSA"
432
);
433
```
434
435
### Session Statistics
436
437
Realm-wide session statistics and monitoring.
438
439
```typescript { .api }
440
/**
441
* Get session statistics for all clients in the realm
442
* @param params - Realm identifier
443
* @returns Array of client session statistics
444
*/
445
getClientsSessionStats(params: { realm: string }): Promise<ClientSessionStat[]>;
446
447
/**
448
* Client session statistics
449
*/
450
interface ClientSessionStat {
451
/** Client ID */
452
clientId?: string;
453
/** Active session count */
454
active?: number;
455
/** Offline session count */
456
offline?: number;
457
}
458
```
459
460
**Usage Examples:**
461
462
```typescript
463
// Get session statistics
464
const sessionStats = await kcAdminClient.realms.getClientsSessionStats({
465
realm: "my-app-realm",
466
});
467
468
sessionStats.forEach(stat => {
469
console.log(`Client ${stat.clientId}: ${stat.active} active, ${stat.offline} offline`);
470
});
471
472
// Find clients with high session counts
473
const highUsageClients = sessionStats.filter(stat =>
474
stat.active && stat.active > 100
475
);
476
```
477
478
## Types
479
480
```typescript { .api }
481
/**
482
* Complete realm configuration representation
483
*/
484
interface RealmRepresentation {
485
/** Realm unique identifier */
486
id?: string;
487
/** Realm name */
488
realm?: string;
489
/** Display name */
490
displayName?: string;
491
/** Display name in HTML format */
492
displayNameHtml?: string;
493
/** Whether realm is enabled */
494
enabled?: boolean;
495
/** SSL requirement level */
496
sslRequired?: "all" | "external" | "none";
497
/** User registration allowed */
498
registrationAllowed?: boolean;
499
/** Registration email as username */
500
registrationEmailAsUsername?: boolean;
501
/** Remember me feature enabled */
502
rememberMe?: boolean;
503
/** Verify email on registration */
504
verifyEmail?: boolean;
505
/** Login with email allowed */
506
loginWithEmailAllowed?: boolean;
507
/** Duplicate emails allowed */
508
duplicateEmailsAllowed?: boolean;
509
/** Password reset allowed */
510
resetPasswordAllowed?: boolean;
511
/** Username editing allowed */
512
editUsernameAllowed?: boolean;
513
/** Brute force protection enabled */
514
bruteForceProtected?: boolean;
515
/** Permanent lockout on brute force */
516
permanentLockout?: boolean;
517
/** Max login failures before lockout */
518
maxFailureWaitSeconds?: number;
519
/** Minimum quick login wait seconds */
520
minimumQuickLoginWaitSeconds?: number;
521
/** Wait increment seconds */
522
waitIncrementSeconds?: number;
523
/** Quick login check milliseconds */
524
quickLoginCheckMilliSeconds?: number;
525
/** Max delta time seconds */
526
maxDeltaTimeSeconds?: number;
527
/** Failed login attempts before wait */
528
failureFactor?: number;
529
/** Default roles for new users */
530
defaultRoles?: string[];
531
/** Required credentials */
532
requiredCredentials?: string[];
533
/** Password policy */
534
passwordPolicy?: string;
535
/** OTP policy */
536
otpPolicyType?: string;
537
/** OTP policy algorithm */
538
otpPolicyAlgorithm?: string;
539
/** OTP policy initial counter */
540
otpPolicyInitialCounter?: number;
541
/** OTP policy digits */
542
otpPolicyDigits?: number;
543
/** OTP policy look ahead window */
544
otpPolicyLookAheadWindow?: number;
545
/** OTP policy period */
546
otpPolicyPeriod?: number;
547
/** Access token lifespan */
548
accessTokenLifespan?: number;
549
/** Access token lifespan for implicit flow */
550
accessTokenLifespanForImplicitFlow?: number;
551
/** SSO session idle timeout */
552
ssoSessionIdleTimeout?: number;
553
/** SSO session max lifespan */
554
ssoSessionMaxLifespan?: number;
555
/** Offline session idle timeout */
556
offlineSessionIdleTimeout?: number;
557
/** Access code lifespan */
558
accessCodeLifespan?: number;
559
/** Access code lifespan user action */
560
accessCodeLifespanUserAction?: number;
561
/** Access code lifespan login */
562
accessCodeLifespanLogin?: number;
563
/** Not before value */
564
notBefore?: number;
565
/** Revoke refresh token */
566
revokeRefreshToken?: boolean;
567
/** Refresh token max reuse */
568
refreshTokenMaxReuse?: number;
569
/** Access token lifespan */
570
accessTokenLifespan?: number;
571
/** Client session idle timeout */
572
clientSessionIdleTimeout?: number;
573
/** Client session max lifespan */
574
clientSessionMaxLifespan?: number;
575
/** Internationalization enabled */
576
internationalizationEnabled?: boolean;
577
/** Supported locales */
578
supportedLocales?: string[];
579
/** Default locale */
580
defaultLocale?: string;
581
/** Browser flow */
582
browserFlow?: string;
583
/** Registration flow */
584
registrationFlow?: string;
585
/** Direct grant flow */
586
directGrantFlow?: string;
587
/** Reset credentials flow */
588
resetCredentialsFlow?: string;
589
/** Client authentication flow */
590
clientAuthenticationFlow?: string;
591
/** Docker authentication flow */
592
dockerAuthenticationFlow?: string;
593
/** Custom attributes */
594
attributes?: Record<string, string>;
595
/** User managed access allowed */
596
userManagedAccessAllowed?: boolean;
597
/** Social providers (deprecated) */
598
socialProviders?: Record<string, string>;
599
/** Identity providers */
600
identityProviders?: IdentityProviderRepresentation[];
601
/** Identity provider mappers */
602
identityProviderMappers?: IdentityProviderMapperRepresentation[];
603
/** Users */
604
users?: UserRepresentation[];
605
/** Groups */
606
groups?: GroupRepresentation[];
607
/** Roles */
608
roles?: {
609
realm?: RoleRepresentation[];
610
client?: Record<string, RoleRepresentation[]>;
611
};
612
/** Clients */
613
clients?: ClientRepresentation[];
614
/** Client scopes */
615
clientScopes?: ClientScopeRepresentation[];
616
/** Default default client scopes */
617
defaultDefaultClientScopes?: string[];
618
/** Default optional client scopes */
619
defaultOptionalClientScopes?: string[];
620
/** Browser security headers */
621
browserSecurityHeaders?: Record<string, string>;
622
/** SMTP server configuration */
623
smtpServer?: Record<string, string>;
624
/** Login theme */
625
loginTheme?: string;
626
/** Account theme */
627
accountTheme?: string;
628
/** Admin theme */
629
adminTheme?: string;
630
/** Email theme */
631
emailTheme?: string;
632
/** Events enabled */
633
eventsEnabled?: boolean;
634
/** Events expiration */
635
eventsExpiration?: number;
636
/** Events listeners */
637
eventsListeners?: string[];
638
/** Enabled event types */
639
enabledEventTypes?: string[];
640
/** Admin events enabled */
641
adminEventsEnabled?: boolean;
642
/** Admin events details enabled */
643
adminEventsDetailsEnabled?: boolean;
644
/** Master admin client */
645
masterAdminClient?: string;
646
}
647
```