A comprehensive TypeScript client library for interacting with Keycloak's Administration API.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Realm configuration, import/export, event management, default groups, and administrative settings.
Basic realm lifecycle management operations.
/**
* Find all realms or search with criteria
* @param query - Optional search criteria
* @returns Array of realm representations
*/
find(query?: { briefRepresentation?: boolean }): Promise<RealmRepresentation[]>;
/**
* Create a new realm
* @param realm - Realm configuration
* @returns Object with created realm name
*/
create(realm: RealmRepresentation): Promise<{ realmName: string }>;
/**
* Find a specific realm by name
* @param params - Realm identifier
* @returns Realm representation or undefined if not found
*/
findOne(params: { realm: string }): Promise<RealmRepresentation | undefined>;
/**
* Update an existing realm configuration
* @param query - Realm identifier
* @param realm - Updated realm configuration
*/
update(query: { realm: string }, realm: RealmRepresentation): Promise<void>;
/**
* Delete a realm
* @param params - Realm identifier
*/
del(params: { realm: string }): Promise<void>;Usage Examples:
// List all realms
const realms = await kcAdminClient.realms.find();
console.log("Available realms:", realms.map(r => r.realm));
// Get brief representation only
const realmsBrief = await kcAdminClient.realms.find({
briefRepresentation: true,
});
// Create new realm
await kcAdminClient.realms.create({
realm: "my-app-realm",
displayName: "My Application Realm",
enabled: true,
sslRequired: "external",
registrationAllowed: true,
loginWithEmailAllowed: true,
duplicateEmailsAllowed: false,
resetPasswordAllowed: true,
editUsernameAllowed: false,
bruteForceProtected: true,
});
// Get specific realm
const realm = await kcAdminClient.realms.findOne({ realm: "my-app-realm" });
console.log("Realm settings:", realm);
// Update realm settings
await kcAdminClient.realms.update(
{ realm: "my-app-realm" },
{
displayName: "My Updated Application Realm",
registrationAllowed: false,
bruteForceProtected: true,
}
);
// Delete realm (careful!)
await kcAdminClient.realms.del({ realm: "test-realm" });Realm import/export functionality for configuration management and migrations.
/**
* Partial import of realm configuration
* @param params - Realm and import configuration
* @returns Import results with conflicts and imported resources
*/
partialImport(params: {
realm: string;
rep: PartialImportRealmRepresentation;
}): Promise<PartialImportResponse>;
/**
* Export realm configuration
* @param params - Export options
* @returns Complete realm representation for export
*/
export(params: {
realm: string;
exportClients?: boolean;
exportGroupsAndRoles?: boolean;
}): Promise<RealmRepresentation>;
/**
* Partial import request configuration
*/
interface PartialImportRealmRepresentation {
/** Import policy for conflicts */
ifResourceExists?: "FAIL" | "SKIP" | "OVERWRITE";
/** Users to import */
users?: UserRepresentation[];
/** Clients to import */
clients?: ClientRepresentation[];
/** Groups to import */
groups?: GroupRepresentation[];
/** Roles to import */
roles?: {
realm?: RoleRepresentation[];
client?: Record<string, RoleRepresentation[]>;
};
/** Identity providers to import */
identityProviders?: IdentityProviderRepresentation[];
}
/**
* Results from partial import operation
*/
interface PartialImportResponse {
/** Number of resources imported */
imported: number;
/** Number of resources skipped */
skipped: number;
/** Import results by resource type */
results: {
users?: number;
clients?: number;
groups?: number;
roles?: number;
identityProviders?: number;
};
}Usage Examples:
// Export realm configuration
const realmExport = await kcAdminClient.realms.export({
realm: "my-app-realm",
exportClients: true,
exportGroupsAndRoles: true,
});
// Save to file or transfer to another environment
console.log("Exported realm config:", JSON.stringify(realmExport, null, 2));
// Partial import with overwrite policy
const importResult = await kcAdminClient.realms.partialImport({
realm: "target-realm",
rep: {
ifResourceExists: "OVERWRITE",
users: [
{
username: "imported-user",
email: "user@example.com",
enabled: true,
},
],
clients: [
{
clientId: "imported-client",
enabled: true,
publicClient: false,
},
],
roles: {
realm: [
{
name: "imported-role",
description: "Role imported from another realm",
},
],
},
},
});
console.log(`Import completed: ${importResult.imported} imported, ${importResult.skipped} skipped`);Management of realm-level default group assignments.
/**
* Get default groups for the realm
* @param params - Realm identifier
* @returns Array of default groups
*/
getDefaultGroups(params: { realm: string }): Promise<GroupRepresentation[]>;
/**
* Add a group to realm default groups
* @param params - Realm and group identifiers
*/
addDefaultGroup(params: { realm: string; id: string }): Promise<void>;
/**
* Remove a group from realm default groups
* @param params - Realm and group identifiers
*/
removeDefaultGroup(params: { realm: string; id: string }): Promise<void>;Usage Examples:
// Get current default groups
const defaultGroups = await kcAdminClient.realms.getDefaultGroups({
realm: "my-app-realm",
});
console.log("Default groups:", defaultGroups.map(g => g.name));
// Add group to defaults (new users will automatically join)
await kcAdminClient.realms.addDefaultGroup({
realm: "my-app-realm",
id: "group-uuid-here",
});
// Remove group from defaults
await kcAdminClient.realms.removeDefaultGroup({
realm: "my-app-realm",
id: "group-uuid-here",
});Configuration and retrieval of audit events and admin events.
/**
* Find user events with optional filtering
* @param params - Realm and event query parameters
* @returns Array of user events
*/
findEvents(params: { realm: string } & EventQuery): Promise<EventRepresentation[]>;
/**
* Get realm events configuration
* @param params - Realm identifier
* @returns Current events configuration
*/
getEventsConfig(params: { realm: string }): Promise<RealmEventsConfigRepresentation>;
/**
* Update realm events configuration
* @param query - Realm identifier
* @param config - New events configuration
*/
updateEventsConfig(
query: { realm: string },
config: RealmEventsConfigRepresentation
): Promise<void>;
/**
* Find admin events with optional filtering
* @param params - Realm and admin event query parameters
* @returns Array of admin events
*/
findAdminEvents(params: { realm: string } & AdminEventQuery): Promise<AdminEventRepresentation[]>;
/**
* Event query parameters for filtering user events
*/
interface EventQuery {
/** Event types to include */
type?: string[];
/** Client ID filter */
client?: string;
/** User ID filter */
user?: string;
/** Date range start */
dateFrom?: string;
/** Date range end */
dateTo?: string;
/** IP address filter */
ipAddress?: string;
/** Maximum number of events to return */
max?: number;
/** Number of events to skip */
first?: number;
}
/**
* Admin event query parameters
*/
interface AdminEventQuery {
/** Operation types to include */
operationTypes?: string[];
/** Authentication realm filter */
authRealm?: string;
/** Authentication client filter */
authClient?: string;
/** Authentication user filter */
authUser?: string;
/** Authentication IP address filter */
authIpAddress?: string;
/** Resource path filter */
resourcePath?: string;
/** Date range start */
dateFrom?: string;
/** Date range end */
dateTo?: string;
/** Maximum number of events to return */
max?: number;
/** Number of events to skip */
first?: number;
}Usage Examples:
// Get recent login events
const loginEvents = await kcAdminClient.realms.findEvents({
realm: "my-app-realm",
type: ["LOGIN", "LOGIN_ERROR"],
dateFrom: "2023-01-01",
max: 100,
});
console.log("Recent login attempts:", loginEvents.length);
// Get admin events
const adminEvents = await kcAdminClient.realms.findAdminEvents({
realm: "my-app-realm",
operationTypes: ["CREATE", "UPDATE", "DELETE"],
authUser: "admin",
max: 50,
});
// Configure event logging
await kcAdminClient.realms.updateEventsConfig(
{ realm: "my-app-realm" },
{
eventsEnabled: true,
eventsExpiration: 2592000, // 30 days
eventsListeners: ["jboss-logging"],
enabledEventTypes: [
"LOGIN",
"LOGIN_ERROR",
"REGISTER",
"LOGOUT",
"CLIENT_LOGIN",
],
adminEventsEnabled: true,
adminEventsDetailsEnabled: true,
}
);Realm cryptographic key management.
/**
* Get realm's cryptographic keys and certificates
* @param params - Realm identifier
* @returns Keys metadata including public keys and certificates
*/
getKeys(params: { realm: string }): Promise<KeysMetadataRepresentation>;
/**
* Cryptographic keys metadata
*/
interface KeysMetadataRepresentation {
/** Active keys */
keys?: KeyMetadataRepresentation[];
/** Available key algorithms */
algorithms?: string[];
}
/**
* Individual key metadata
*/
interface KeyMetadataRepresentation {
/** Key provider ID */
providerId?: string;
/** Provider priority */
providerPriority?: number;
/** Key ID */
kid?: string;
/** Key status */
status?: "ACTIVE" | "PASSIVE" | "DISABLED";
/** Key type */
type?: string;
/** Key algorithm */
algorithm?: string;
/** Public key */
publicKey?: string;
/** X.509 certificate */
certificate?: string;
}Usage Examples:
// Get realm keys
const keys = await kcAdminClient.realms.getKeys({ realm: "my-app-realm" });
console.log("Available algorithms:", keys.algorithms);
console.log("Active keys:", keys.keys?.filter(k => k.status === "ACTIVE"));
// Find RSA signing keys
const rsaKeys = keys.keys?.filter(k =>
k.algorithm === "RS256" && k.type === "RSA"
);Realm-wide session statistics and monitoring.
/**
* Get session statistics for all clients in the realm
* @param params - Realm identifier
* @returns Array of client session statistics
*/
getClientsSessionStats(params: { realm: string }): Promise<ClientSessionStat[]>;
/**
* Client session statistics
*/
interface ClientSessionStat {
/** Client ID */
clientId?: string;
/** Active session count */
active?: number;
/** Offline session count */
offline?: number;
}Usage Examples:
// Get session statistics
const sessionStats = await kcAdminClient.realms.getClientsSessionStats({
realm: "my-app-realm",
});
sessionStats.forEach(stat => {
console.log(`Client ${stat.clientId}: ${stat.active} active, ${stat.offline} offline`);
});
// Find clients with high session counts
const highUsageClients = sessionStats.filter(stat =>
stat.active && stat.active > 100
);/**
* Complete realm configuration representation
*/
interface RealmRepresentation {
/** Realm unique identifier */
id?: string;
/** Realm name */
realm?: string;
/** Display name */
displayName?: string;
/** Display name in HTML format */
displayNameHtml?: string;
/** Whether realm is enabled */
enabled?: boolean;
/** SSL requirement level */
sslRequired?: "all" | "external" | "none";
/** User registration allowed */
registrationAllowed?: boolean;
/** Registration email as username */
registrationEmailAsUsername?: boolean;
/** Remember me feature enabled */
rememberMe?: boolean;
/** Verify email on registration */
verifyEmail?: boolean;
/** Login with email allowed */
loginWithEmailAllowed?: boolean;
/** Duplicate emails allowed */
duplicateEmailsAllowed?: boolean;
/** Password reset allowed */
resetPasswordAllowed?: boolean;
/** Username editing allowed */
editUsernameAllowed?: boolean;
/** Brute force protection enabled */
bruteForceProtected?: boolean;
/** Permanent lockout on brute force */
permanentLockout?: boolean;
/** Max login failures before lockout */
maxFailureWaitSeconds?: number;
/** Minimum quick login wait seconds */
minimumQuickLoginWaitSeconds?: number;
/** Wait increment seconds */
waitIncrementSeconds?: number;
/** Quick login check milliseconds */
quickLoginCheckMilliSeconds?: number;
/** Max delta time seconds */
maxDeltaTimeSeconds?: number;
/** Failed login attempts before wait */
failureFactor?: number;
/** Default roles for new users */
defaultRoles?: string[];
/** Required credentials */
requiredCredentials?: string[];
/** Password policy */
passwordPolicy?: string;
/** OTP policy */
otpPolicyType?: string;
/** OTP policy algorithm */
otpPolicyAlgorithm?: string;
/** OTP policy initial counter */
otpPolicyInitialCounter?: number;
/** OTP policy digits */
otpPolicyDigits?: number;
/** OTP policy look ahead window */
otpPolicyLookAheadWindow?: number;
/** OTP policy period */
otpPolicyPeriod?: number;
/** Access token lifespan */
accessTokenLifespan?: number;
/** Access token lifespan for implicit flow */
accessTokenLifespanForImplicitFlow?: number;
/** SSO session idle timeout */
ssoSessionIdleTimeout?: number;
/** SSO session max lifespan */
ssoSessionMaxLifespan?: number;
/** Offline session idle timeout */
offlineSessionIdleTimeout?: number;
/** Access code lifespan */
accessCodeLifespan?: number;
/** Access code lifespan user action */
accessCodeLifespanUserAction?: number;
/** Access code lifespan login */
accessCodeLifespanLogin?: number;
/** Not before value */
notBefore?: number;
/** Revoke refresh token */
revokeRefreshToken?: boolean;
/** Refresh token max reuse */
refreshTokenMaxReuse?: number;
/** Access token lifespan */
accessTokenLifespan?: number;
/** Client session idle timeout */
clientSessionIdleTimeout?: number;
/** Client session max lifespan */
clientSessionMaxLifespan?: number;
/** Internationalization enabled */
internationalizationEnabled?: boolean;
/** Supported locales */
supportedLocales?: string[];
/** Default locale */
defaultLocale?: string;
/** Browser flow */
browserFlow?: string;
/** Registration flow */
registrationFlow?: string;
/** Direct grant flow */
directGrantFlow?: string;
/** Reset credentials flow */
resetCredentialsFlow?: string;
/** Client authentication flow */
clientAuthenticationFlow?: string;
/** Docker authentication flow */
dockerAuthenticationFlow?: string;
/** Custom attributes */
attributes?: Record<string, string>;
/** User managed access allowed */
userManagedAccessAllowed?: boolean;
/** Social providers (deprecated) */
socialProviders?: Record<string, string>;
/** Identity providers */
identityProviders?: IdentityProviderRepresentation[];
/** Identity provider mappers */
identityProviderMappers?: IdentityProviderMapperRepresentation[];
/** Users */
users?: UserRepresentation[];
/** Groups */
groups?: GroupRepresentation[];
/** Roles */
roles?: {
realm?: RoleRepresentation[];
client?: Record<string, RoleRepresentation[]>;
};
/** Clients */
clients?: ClientRepresentation[];
/** Client scopes */
clientScopes?: ClientScopeRepresentation[];
/** Default default client scopes */
defaultDefaultClientScopes?: string[];
/** Default optional client scopes */
defaultOptionalClientScopes?: string[];
/** Browser security headers */
browserSecurityHeaders?: Record<string, string>;
/** SMTP server configuration */
smtpServer?: Record<string, string>;
/** Login theme */
loginTheme?: string;
/** Account theme */
accountTheme?: string;
/** Admin theme */
adminTheme?: string;
/** Email theme */
emailTheme?: string;
/** Events enabled */
eventsEnabled?: boolean;
/** Events expiration */
eventsExpiration?: number;
/** Events listeners */
eventsListeners?: string[];
/** Enabled event types */
enabledEventTypes?: string[];
/** Admin events enabled */
adminEventsEnabled?: boolean;
/** Admin events details enabled */
adminEventsDetailsEnabled?: boolean;
/** Master admin client */
masterAdminClient?: string;
}docs