User API
The UserHandle class provides a fluent API for managing Keycloak users. It allows you to create, update, delete, and manage user roles, groups, and other attributes within a specific realm.
Class: UserHandle
Constructor
constructor(core: KeycloakAdminClient, realmHandle: RealmHandle, username: string)
- Parameters:
core: An instance ofKeycloakAdminClient.realmHandle: A handle to the realm where the user resides.username: The username of the user to manage.
Instance Methods
get()
Fetches the user by their username.
public async get(): Promise<UserRepresentation | null>
- Returns: The user representation or
nullif the user does not exist.
create(data: UserInputData)
Creates a new user.
public async create(data: UserInputData)
- Parameters:
data: The data for the new user, including optional password.
- Throws: An error if the user already exists.
Password provisioning failure semantics
When data.password is provided, the user is created with enabled: false
first, the password is reset against the disabled account, and only then is
the user enabled (unless data.enabled is explicitly false, in which case
the account stays disabled after a successful password setup). This means a
password-reset failure can never leave an enabled, usable account.
On a password failure during creation, the just-created disabled user is
deleted best-effort so retrying starts clean. If the deletion also fails, the
disabled account is left behind (it is unusable) and the original password
error is rethrown as a UserPasswordProvisioningError with the cleanup
failure annotated on cause. The plaintext password is never included in the
error, its cause, or any serialized form.
update(data: UserInputData)
Updates the user's details.
public async update(data: UserInputData)
- Parameters:
data: The updated data for the user, including optional password.
- Throws: An error if the user does not exist.
Partial-success semantics
If a password is supplied, the profile update is applied first and the
password reset runs second. A password-reset failure does not roll back
the preceding profile update (it has already been committed in Keycloak).
Instead a UserPasswordProvisioningError is thrown with profileApplied: true
and initialProvisioning: false; the caller can retry the password step
explicitly or otherwise remediate. The plaintext password is never included in
the error or its cause.
delete()
Deletes the user.
public async delete()
- Throws: An error if the user does not exist.
ensure(data: UserInputData)
Ensures the user exists. If they do, updates them; otherwise, creates them.
public async ensure(data: UserInputData)
- Parameters:
data: The data for the user, including optional password.
On the create branch, ensure uses the same disabled-until-password-success
semantics as create. On the update branch, it uses the same partial-success
semantics as update.
discard()
Deletes the user if they exist.
public async discard()
- Returns: The username of the deleted user.
assignRole(roleHandle: RoleHandle)
Assigns a realm role to the user.
public async assignRole(roleHandle: RoleHandle)
- Parameters:
roleHandle: A handle to the realm role to assign.
- Throws: An error if the role does not exist.
unassignRole(roleHandle: RoleHandle)
Unassigns a realm role from the user.
public async unassignRole(roleHandle: RoleHandle)
- Parameters:
roleHandle: A handle to the realm role to unassign.
- Throws: An error if the role does not exist.
assignClientRole(clientRoleHandle: ClientRoleHandle)
Assigns a client role to the user.
public async assignClientRole(clientRoleHandle: ClientRoleHandle)
- Parameters:
clientRoleHandle: A handle to the client role to assign.
- Throws: An error if the client or role does not exist.
unassignClientRole(clientRoleHandle: ClientRoleHandle)
Unassigns a client role from the user.
public async unassignClientRole(clientRoleHandle: ClientRoleHandle)
- Parameters:
clientRoleHandle: A handle to the client role to unassign.
- Throws: An error if the client or role does not exist.
listAssignedClientRoles(clientHandle: ClientHandle)
Lists all client roles assigned to the user for a specific client.
public async listAssignedClientRoles(clientHandle: ClientHandle)
- Parameters:
clientHandle: A handle to the client.
- Returns: A list of assigned client roles.
assignGroup(groupHandle: AbstractGroupHandle)
Assigns the user to a group.
public async assignGroup(groupHandle: AbstractGroupHandle)
- Parameters:
groupHandle: A handle to the group to assign.
- Throws: An error if the group does not exist.
unassignGroup(groupHandle: AbstractGroupHandle)
Removes the user from a group.
public async unassignGroup(groupHandle: AbstractGroupHandle)
- Parameters:
groupHandle: A handle to the group to unassign.
- Throws: An error if the group does not exist.
listAssignedGroups()
Lists all groups the user is assigned to.
public async listAssignedGroups()
- Returns: A list of assigned groups.
Constants
defaultUserData
Default data for creating a user.
export const defaultUserData = Object.freeze({
firstName: '',
lastName: '',
email: '',
emailVerified: false,
enabled: true,
totp: false,
disableableCredentialTypes: [],
requiredActions: [],
notBefore: 0,
access: {
manageGroupMembership: true,
resetPassword: true,
view: true,
mapRoles: true,
impersonate: true,
manage: true,
},
attributes: {},
});
Types
UserInputData
The input data type for creating or updating a user.
import type { UserInputData } from '@egose/keycloak-fluent';
export type UserInputData = Omit<UserRepresentation, 'username' | 'id'> & {
password?: string;
/** Whether a supplied password must be changed on first login. Defaults to false. */
passwordTemporary?: boolean;
};
UserPasswordProvisioningError
Error thrown when password setup fails after user profile data has been
applied. The plaintext password is never present in any field of this error
or its sanitized cause. Import it from the package root:
import { UserPasswordProvisioningError } from '@egose/keycloak-fluent';
export class UserPasswordProvisioningError extends Error {
readonly username: string;
readonly realmName: string;
/** true when profile state is known to persist in Keycloak. */
readonly profileApplied: boolean;
/** true when a user account is known to persist in Keycloak after the failure. */
readonly accountPersists: boolean;
/** the known enabled state of the persisted account, or null when unknown/not persisted. */
readonly accountEnabled: boolean | null;
/** true when the supplied password was committed before a later provisioning step failed. */
readonly passwordApplied: boolean;
/** true for the create/ensure-create path; false for updates of an existing user. */
readonly initialProvisioning: boolean;
}
- On the create / ensure-create path, a password failure triggers a
best-effort deletion of the just-created disabled user. When that deletion
succeeds,
accountPersistsisfalse,accountEnabledisnull, andpasswordAppliedisfalse. When deletion also fails,accountPersistsandprofileAppliedaretrue,accountEnabledisfalse, and the sanitized publiccausereports both the password and cleanup failures. - On the update path, the profile update has already committed and is not
rolled back.
profileAppliedandaccountPersistsaretrue,passwordAppliedisfalse, andinitialProvisioningisfalse. - If the final enable step fails after a password was applied,
passwordAppliedistrue,accountPersistsistrue, andaccountEnabledisfalse. Retrying withensure()and the same enabled input updates and enables the existing user instead of creating a duplicate.
This API provides a comprehensive interface for managing Keycloak users and their associated roles, groups, and attributes.