CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-keycloak--keycloak-admin-client

A comprehensive TypeScript client library for interacting with Keycloak's Administration API.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

user-management.mddocs/

User Management

The Users resource provides comprehensive functionality for managing user accounts, including CRUD operations, role mappings, group memberships, credentials, sessions, and security actions.

Capabilities

User CRUD Operations

Basic user lifecycle management including creation, retrieval, updates, and deletion.

/**
 * User query interface for filtering and pagination
 */
interface UserQuery extends PaginationQuery, SearchQuery, UserBaseQuery {
  /** Exact match search instead of substring matching */
  exact?: boolean;
  /** Allow additional dynamic query parameters */
  [key: string]: string | number | undefined | boolean;
}

interface PaginationQuery {
  /** Starting index for pagination (0-based) */
  first?: number;
  /** Maximum number of results to return */
  max?: number;
}

interface SearchQuery {
  /** General search term across multiple user fields */
  search?: string;
}

interface UserBaseQuery {
  /** Filter by email address */
  email?: string;
  /** Filter by first name */
  firstName?: string;
  /** Filter by last name */
  lastName?: string;
  /** Filter by username */
  username?: string;
  /** Query string for advanced search */
  q?: string;
}

/**
 * Find users with optional filtering and pagination
 * @param query - Optional query parameters for filtering users
 * @returns Array of user representations
 */
find(query?: UserQuery): Promise<UserRepresentation[]>;

/**
 * Create a new user
 * @param user - User representation with user details
 * @returns Object containing the ID of the created user
 */
create(user: UserRepresentation): Promise<{ id: string }>;

/**
 * Get a single user by ID
 * @param params - Parameters including user ID and optional metadata flag
 * @returns User representation or undefined if not found
 */
findOne(params: { id: string; userProfileMetadata?: boolean }): Promise<UserRepresentation | undefined>;

/**
 * Update an existing user
 * @param query - Query containing user ID
 * @param user - Updated user representation
 */
update(query: { id: string }, user: UserRepresentation): Promise<void>;

/**
 * Delete a user
 * @param params - Parameters containing user ID
 */
del(params: { id: string }): Promise<void>;

/**
 * Count total number of users matching query
 * @param query - Optional query parameters for filtering
 * @returns Total count of matching users
 */
count(query?: UserBaseQuery & SearchQuery): Promise<number>;

Usage Examples:

// Find all users with pagination
const users = await kcAdminClient.users.find({
  first: 0,
  max: 20,
});

// Search users by email domain
const companyUsers = await kcAdminClient.users.find({
  email: "@company.com",
  exact: false,
});

// Create a new user
const { id } = await kcAdminClient.users.create({
  username: "johndoe",
  email: "john.doe@example.com",
  firstName: "John",
  lastName: "Doe",
  enabled: true,
  emailVerified: false,
  attributes: {
    department: ["Engineering"],
    location: ["New York"],
  },
});

// Update user details
await kcAdminClient.users.update({ id }, {
  firstName: "Jonathan",
  emailVerified: true,
  attributes: {
    department: ["Engineering"],
    location: ["San Francisco"],
  },
});

// Get user with profile metadata
const user = await kcAdminClient.users.findOne({ 
  id, 
  userProfileMetadata: true 
});

// Count users
const totalUsers = await kcAdminClient.users.count();
const activeUsers = await kcAdminClient.users.count({ 
  search: "enabled:true" 
});

User Representation

Complete TypeScript interface for user data structure.

/**
 * Complete user representation with all available fields
 */
interface UserRepresentation {
  /** Unique user identifier */
  id?: string;
  /** Timestamp when user was created */
  createdTimestamp?: number;
  /** Unique username for authentication */
  username?: string;
  /** Whether the user account is enabled */
  enabled?: boolean;
  /** Whether user has TOTP configured */
  totp?: boolean;
  /** Whether user's email is verified */
  emailVerified?: boolean;
  /** Credential types that can be disabled for this user */
  disableableCredentialTypes?: string[];
  /** Required actions that must be completed */
  requiredActions?: (RequiredActionAlias | string)[];
  /** Not-before policy timestamp */
  notBefore?: number;
  /** Access control permissions */
  access?: Record<string, boolean>;

  // Optional profile fields
  /** Custom user attributes */
  attributes?: Record<string, any>;
  /** User consent information */
  clientConsents?: UserConsentRepresentation[];
  /** Client-specific role mappings */
  clientRoles?: Record<string, any>;
  /** User credentials */
  credentials?: CredentialRepresentation[];
  /** Email address */
  email?: string;
  /** Federated identity links */
  federatedIdentities?: FederatedIdentityRepresentation[];
  /** Federation link identifier */
  federationLink?: string;
  /** First name */
  firstName?: string;
  /** Group memberships */
  groups?: string[];
  /** Last name */
  lastName?: string;
  /** Realm-level role assignments */
  realmRoles?: string[];
  /** Self-reference URL */
  self?: string;
  /** Service account client ID (if user is a service account) */
  serviceAccountClientId?: string;
  /** User profile metadata */
  userProfileMetadata?: UserProfileMetadata;
}

/**
 * Required action types that can be assigned to users
 */
enum RequiredActionAlias {
  VERIFY_EMAIL = "VERIFY_EMAIL",
  UPDATE_PROFILE = "UPDATE_PROFILE", 
  CONFIGURE_TOTP = "CONFIGURE_TOTP",
  UPDATE_PASSWORD = "UPDATE_PASSWORD",
  TERMS_AND_CONDITIONS = "TERMS_AND_CONDITIONS",
}

User Profile Management

User profile configuration and metadata management for advanced user schemas.

/**
 * Get user profile configuration for the realm
 * @returns User profile configuration
 */
getProfile(): Promise<UserProfileConfig>;

/**
 * Update user profile configuration
 * @param profile - New profile configuration
 * @returns Updated profile configuration
 */
updateProfile(profile: UserProfileConfig): Promise<UserProfileConfig>;

/**
 * Get user profile metadata
 * @returns Profile metadata including attribute definitions
 */
getProfileMetadata(): Promise<UserProfileMetadata>;

Role Mappings

Complete role mapping management for both realm and client roles.

/**
 * List all role mappings for a user (realm and client roles)
 * @param params - Parameters containing user ID
 * @returns Complete role mappings representation
 */
listRoleMappings(params: { id: string }): Promise<MappingsRepresentation>;

/**
 * Add realm role mappings to user
 * @param params - User ID and roles to add
 */
addRealmRoleMappings(params: { id: string; roles: RoleMappingPayload[] }): Promise<void>;

/**
 * List realm role mappings for user
 * @param params - Parameters containing user ID
 * @returns Array of realm roles assigned to user
 */
listRealmRoleMappings(params: { id: string }): Promise<RoleRepresentation[]>;

/**
 * Remove realm role mappings from user
 * @param params - User ID and roles to remove
 */
delRealmRoleMappings(params: { id: string; roles: RoleMappingPayload[] }): Promise<void>;

/**
 * List available realm roles that can be assigned to user
 * @param params - Parameters containing user ID
 * @returns Array of available realm roles
 */
listAvailableRealmRoleMappings(params: { id: string }): Promise<RoleRepresentation[]>;

/**
 * List effective realm role mappings (including composite roles)
 * @param params - Parameters containing user ID
 * @returns Array of effective realm roles
 */
listCompositeRealmRoleMappings(params: { id: string }): Promise<RoleRepresentation[]>;

Role Mapping Examples:

// Assign realm roles to user
await kcAdminClient.users.addRealmRoleMappings({
  id: userId,
  roles: [
    { id: "admin-role-id", name: "admin" },
    { id: "user-role-id", name: "user" },
  ],
});

// List user's current realm roles
const realmRoles = await kcAdminClient.users.listRealmRoleMappings({ id: userId });

// Remove specific realm role
await kcAdminClient.users.delRealmRoleMappings({
  id: userId,
  roles: [{ id: "user-role-id", name: "user" }],
});

// Check available roles for assignment
const availableRoles = await kcAdminClient.users.listAvailableRealmRoleMappings({ 
  id: userId 
});

Client Role Mappings

Management of client-specific role assignments.

/**
 * List client role mappings for user
 * @param params - User ID and client unique ID
 * @returns Array of client roles assigned to user
 */
listClientRoleMappings(params: { id: string; clientUniqueId: string }): Promise<RoleRepresentation[]>;

/**
 * Add client role mappings to user
 * @param params - User ID, client ID, and roles to add
 */
addClientRoleMappings(params: { id: string; clientUniqueId: string; roles: RoleMappingPayload[] }): Promise<void>;

/**
 * Remove client role mappings from user
 * @param params - User ID, client ID, and roles to remove
 */
delClientRoleMappings(params: { id: string; clientUniqueId: string; roles: RoleMappingPayload[] }): Promise<void>;

/**
 * List available client roles for assignment
 * @param params - User ID and client unique ID
 * @returns Array of available client roles
 */
listAvailableClientRoleMappings(params: { id: string; clientUniqueId: string }): Promise<RoleRepresentation[]>;

/**
 * List effective client role mappings (including composite roles)
 * @param params - User ID and client unique ID
 * @returns Array of effective client roles
 */
listCompositeClientRoleMappings(params: { id: string; clientUniqueId: string }): Promise<RoleRepresentation[]>;

/**
 * Role mapping payload interface for assignment operations
 */
interface RoleMappingPayload extends RoleRepresentation {
  /** Role ID (required for mapping operations) */
  id: string;
  /** Role name (required for mapping operations) */
  name: string;
}

Client Role Examples:

// Assign client roles to user
await kcAdminClient.users.addClientRoleMappings({
  id: userId,
  clientUniqueId: "my-client-id",
  roles: [
    { id: "client-role-id", name: "client-admin" },
    { id: "another-role-id", name: "client-user" },
  ],
});

// List user's roles for specific client
const clientRoles = await kcAdminClient.users.listClientRoleMappings({
  id: userId,
  clientUniqueId: "my-client-id",
});

Group Management

User group membership operations.

/**
 * List groups that a user belongs to
 * @param params - User ID with optional pagination and search
 * @returns Array of groups the user is a member of
 */
listGroups(params: { 
  id: string; 
  briefRepresentation?: boolean; 
} & PaginationQuery & SearchQuery): Promise<GroupRepresentation[]>;

/**
 * Add user to a group
 * @param params - User ID and group ID
 * @returns Success message
 */
addToGroup(params: { id: string; groupId: string }): Promise<string>;

/**
 * Remove user from a group
 * @param params - User ID and group ID  
 * @returns Success message
 */
delFromGroup(params: { id: string; groupId: string }): Promise<string>;

/**
 * Count number of groups user belongs to
 * @param params - User ID with optional search
 * @returns Object containing the count
 */
countGroups(params: { id: string; search?: string }): Promise<{ count: number }>;

Group Management Examples:

// Add user to group
await kcAdminClient.users.addToGroup({
  id: userId,
  groupId: "engineering-group-id",
});

// List user's groups
const userGroups = await kcAdminClient.users.listGroups({
  id: userId,
  briefRepresentation: true,
});

// Remove from group
await kcAdminClient.users.delFromGroup({
  id: userId, 
  groupId: "old-group-id",
});

Credential Management

User credential and password management operations.

/**
 * Reset user's password
 * @param params - User ID and new credential
 */
resetPassword(params: { id: string; credential: CredentialRepresentation }): Promise<void>;

/**
 * Remove TOTP configuration from user
 * @param params - Parameters containing user ID
 */
removeTotp(params: { id: string }): Promise<void>;

/**
 * Get user's configured credential types from user storage
 * @param params - Parameters containing user ID
 * @returns Array of credential type names
 */
getUserStorageCredentialTypes(params: { id: string }): Promise<string[]>;

/**
 * Get user's credentials
 * @param params - Parameters containing user ID
 * @returns Array of user credentials
 */
getCredentials(params: { id: string }): Promise<CredentialRepresentation[]>;

/**
 * Delete a specific credential
 * @param params - User ID and credential ID
 */
deleteCredential(params: { id: string; credentialId: string }): Promise<void>;

/**
 * Update credential label
 * @param query - User ID and credential ID
 * @param label - New label for the credential
 */
updateCredentialLabel(query: { id: string; credentialId: string }, label: string): Promise<void>;

/**
 * Move credential position down in the list
 * @param params - User ID, credential ID, and new previous credential ID
 */
moveCredentialPositionDown(params: {
  id: string;
  credentialId: string;
  newPreviousCredentialId: string;
}): Promise<void>;

/**
 * Move credential to first position
 * @param params - User ID and credential ID
 */
moveCredentialPositionUp(params: { id: string; credentialId: string }): Promise<void>;

/**
 * Credential representation for password and authentication data
 */
interface CredentialRepresentation {
  /** Creation timestamp */
  createdDate?: number;
  /** Encrypted credential data */
  credentialData?: string;
  /** Credential unique identifier */
  id?: string;
  /** Priority for credential ordering */
  priority?: number;
  /** Encrypted secret data */
  secretData?: string;
  /** Whether credential is temporary */
  temporary?: boolean;
  /** Type of credential (password, totp, etc.) */
  type?: string;
  /** User-defined label */
  userLabel?: string;
  /** Credential value (for temporary passwords) */
  value?: string;
  /** Federation link reference */
  federationLink?: string;
}

Credential Management Examples:

// Reset user password
await kcAdminClient.users.resetPassword({
  id: userId,
  credential: {
    type: "password",
    value: "newSecurePassword123",
    temporary: false, // User won't need to change on first login
  },
});

// Set temporary password (user must change on next login)
await kcAdminClient.users.resetPassword({
  id: userId,
  credential: {
    type: "password",
    value: "temporaryPassword",
    temporary: true,
  },
});

// Get user credentials
const credentials = await kcAdminClient.users.getCredentials({ id: userId });

// Remove TOTP
await kcAdminClient.users.removeTotp({ id: userId });

Email Actions

Send email notifications and verification requests to users.

/**
 * Send action email to user with required actions to complete
 * @param params - User ID and email action configuration
 */
executeActionsEmail(params: {
  id: string;
  /** Client ID for redirect context */
  clientId?: string;
  /** Email link lifespan in seconds */
  lifespan?: number;
  /** Redirect URI after actions completion */
  redirectUri?: string;
  /** Required actions to include in email */
  actions?: (RequiredActionAlias | string)[];
}): Promise<void>;

/**
 * Send email verification to user
 * @param params - User ID with optional client context
 */
sendVerifyEmail(params: { 
  id: string; 
  clientId?: string; 
  redirectUri?: string; 
}): Promise<void>;

Email Examples:

// Send password reset email
await kcAdminClient.users.executeActionsEmail({
  id: userId,
  clientId: "my-app",
  redirectUri: "https://myapp.com/auth/callback",
  lifespan: 3600, // 1 hour
  actions: ["UPDATE_PASSWORD"],
});

// Send profile update email
await kcAdminClient.users.executeActionsEmail({
  id: userId,
  actions: ["UPDATE_PROFILE", "VERIFY_EMAIL"],
});

// Send email verification
await kcAdminClient.users.sendVerifyEmail({
  id: userId,
  clientId: "my-app",
  redirectUri: "https://myapp.com/verified",
});

Session Management

User session monitoring and management.

/**
 * List active user sessions
 * @param params - Parameters containing user ID
 * @returns Array of active user sessions
 */
listSessions(params: { id: string }): Promise<UserSessionRepresentation[]>;

/**
 * List offline sessions for user and client
 * @param params - User ID and client ID
 * @returns Array of offline sessions
 */
listOfflineSessions(params: { id: string; clientId: string }): Promise<UserSessionRepresentation[]>;

/**
 * Logout user from all sessions
 * @param params - Parameters containing user ID
 */
logout(params: { id: string }): Promise<void>;

Consent Management

User consent and application permissions management.

/**
 * List user's granted consents
 * @param params - Parameters containing user ID
 * @returns Array of user consent representations
 */
listConsents(params: { id: string }): Promise<UserConsentRepresentation[]>;

/**
 * Revoke user consent for specific client
 * @param params - User ID and client ID
 */
revokeConsent(params: { id: string; clientId: string }): Promise<void>;

Federated Identity

External identity provider link management.

/**
 * List federated identities linked to user
 * @param params - Parameters containing user ID
 * @returns Array of federated identity links
 */
listFederatedIdentities(params: { id: string }): Promise<FederatedIdentityRepresentation[]>;

/**
 * Add federated identity link to user
 * @param params - User ID, provider ID, and federated identity details
 */
addToFederatedIdentity(params: {
  id: string;
  federatedIdentityId: string;
  federatedIdentity: FederatedIdentityRepresentation;
}): Promise<void>;

/**
 * Remove federated identity link from user
 * @param params - User ID and federated identity provider ID
 */
delFromFederatedIdentity(params: { id: string; federatedIdentityId: string }): Promise<void>;

Advanced Operations

Additional user management operations for impersonation and attributes.

/**
 * Impersonate a user (admin capability)
 * @param query - User ID to impersonate
 * @param payload - Impersonation context
 * @returns Impersonation result data
 */
impersonation(query: { id: string }, payload: { user: string; realm: string }): Promise<Record<string, any>>;

/**
 * Get unmanaged user attributes
 * @param params - Parameters containing user ID
 * @returns Record of attribute names to value arrays
 */
getUnmanagedAttributes(params: { id: string }): Promise<Record<string, string[]>>;

docs

attack-detection.md

authentication-management.md

cache-management.md

client-configuration.md

client-management.md

client-policies.md

client-scopes.md

components.md

group-management.md

identity-providers.md

index.md

organization-management.md

realm-management.md

role-management.md

server-info.md

user-management.md

user-storage-provider.md

utility-functions.md

whoami.md

tile.json