Chuyển đến nội dung chính

Lesson 4: Managing Users, Groups and User Profile

Create and manage Users, set credentials, user attributes schema, User Profile configuration, custom attributes and validators, create Groups and sub-groups, group attributes, group role mappings, user self-registration, required actions, impersonation and personal data management.

Keycloak Users, Groups, Roles Hierarchy

Users, Groups and Roles hierarchical model in Keycloak Realm

1. Managing Users

Users is the central entity of Keycloak — representing users who can log into the system. Each user belongs to a specific realm and can have attributes, credentials, roles, and group memberships.

1.1 Create User via Admin Console

  1. Select realm (e.g. my-company) from realm selector

  2. Click Users trong sidebar

  3. Click Add user

  4. Fill in information:

    • Username: john.doe (required)
    • Email: [email protected]
    • First name: John
    • Last name: Doe
    • Email verified: ON (if email verified)
    • Enabled: ON
  5. Click Create

1.2 Create User via Admin CLI

# Tạo user cơ bản
bin/kcadm.sh create users \
  -r my-company \
  -s username=john.doe \
  -s [email protected] \
  -s firstName=John \
  -s lastName=Doe \
  -s enabled=true \
  -s emailVerified=true

Lấy user ID vừa tạo

USER_ID=$(bin/kcadm.sh get users -r my-company -q username=john.doe --fields id --format csv --noquotes)

echo "User ID: $USER_ID"

1.3 Create User via REST API

# Tạo user mới
curl -s -X POST \
  "http://localhost:8080/admin/realms/my-company/users" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john.doe",
    "email": "[email protected]",
    "firstName": "John",
    "lastName": "Doe",
    "enabled": true,
    "emailVerified": true,
    "attributes": {
      "department": ["Engineering"],
      "employee_id": ["EMP001"]
    }
  }'

Lấy user ID từ response header Location

Location: http://localhost:8080/admin/realms/my-company/users/{user-id}

2. Set Credentials

2.1 Set password via Admin Console

  1. Go to Users → select user → tab Credentials

  2. Click Set password

  3. Enter new password

  4. Temporary: ON (user must change password when logging in for the first time) or OFF (fixed password)

  5. Click Save

2.2 Set password via CLI

# Đặt password cố định
bin/kcadm.sh set-password \
  -r my-company \
  --username john.doe \
  --new-password "SecureP@ssw0rd!"

Đặt password tạm thời (bắt đổi khi login)

bin/kcadm.sh set-password
-r my-company
--username john.doe
--new-password "TempP@ss123"
--temporary

2.3 Set password via REST API

# Lấy user ID
USER_ID=$(curl -s -X GET \
  "http://localhost:8080/admin/realms/my-company/users?username=john.doe" \
  -H "Authorization: Bearer $ACCESS_TOKEN" | jq -r '.[0].id')

Đặt password

curl -s -X PUT
"http://localhost:8080/admin/realms/my-company/users/$USER_ID/reset-password"
-H "Authorization: Bearer $ACCESS_TOKEN"
-H "Content-Type: application/json"
-d '{ "type": "password", "value": "SecureP@ssw0rd!", "temporary": false }'

2.4 Password Policies

Configure password policies for realm at Authentication → Policies → Password policy:

PolicyDescriptionExample value
Minimum lengthMinimum length8
Uppercase charactersUppercase characters required1
Lowercase charactersLowercase characters required1
DigitsRequest number1
Special charactersSpecial characters required1
Not usernamePassword must not be the same as username-
Not emailPassword must not match email-
Password historyDo not reuse old password3
Expire passwordPassword expiration time (days)90
Hashing algorithmAlgorithm hash passwordargon2
Hashing iterationsNumber of hashing rounds5 (argon2)

Configuration via CLI:

bin/kcadm.sh update realms/my-company \
  -s 'passwordPolicy="length(8) and upperCase(1) and lowerCase(1) and digits(1) and specialChars(1) and notUsername and passwordHistory(3)"'

3. User Profile

User Profile is a feature that allows administrators to define a schema for user attributes — controlling which attributes users have, how they are validated, and how they are displayed on the interface.

3.1 Enable User Profile

From Keycloak 24+, User Profile is enabled by default. For older versions:

  1. Go to Realm settings → General

  2. Find User profile enabled: ON

Once enabled, access Realm settings → User profile to configure.

3.2 Definition of Attribute Schema

Each attribute has the following configurations:

  • Name — attribute name (lowercase, used for API)

  • Display name — UI display name (i18n support: ${profile.attribute.department})

  • Permissions — who can view/edit (admin, user)

  • Validations — rules validate value

  • Annotations — metadata cho UI rendering

  • Required — required for users, admins, or both

  • Multivalued — allows multiple values

3.3 Built-in Attributes

Keycloak has available attributes:

AttributeDescriptionDefault
usernameUsernameRequired, unique
emailEmail addressRequired (can be turned off)
firstNameNameRequired
lastNameLastNameRequired

3.4 Create Custom Attribute

Example of creating attribute phone_number:

  1. Go to Realm settings → User profile

  2. Click Create attribute

  3. Configuration:

    • Name: phone_number
    • Display name: Phone Number
    • Attribute group: (select or create new)
    • Enabled when: Always
    • Required: Required for user

3.5 Validators

Keycloak provides many validators to check attribute values:

ValidatorDescriptionExample configuration
lengthLength limitmin: 3, max: 50
emailCheck email format-
patternCheck regex pattern^\\+[0-9]{10,15}$
integerInteger checkmin: 0, max: 999999
doubleCheck real numbermin: 0.0, max: 100.0
uriCheck valid URL-
optionsLimit value in list["vn","us","jp"]
person-name-prohibited-charactersProhibit special characters in name-
username-prohibited-charactersProhibit special characters in username-
multivaluedValidate quantity valuesmin: 1, max: 5

Example configuration of attribute phone_number via JSON (User Profile tab → JSON editor):

{
  "attributes": [
    {
      "name": "phone_number",
      "displayName": "Phone Number",
      "validations": {
        "length": {
          "min": 10,
          "max": 15
        },
        "pattern": {
          "pattern": "^\\+[0-9]{10,15}$",
          "error-message": "Phone number must start with + and contain 10-15 digits"
        }
      },
      "required": {
        "roles": ["user"]
      },
      "permissions": {
        "view": ["admin", "user"],
        "edit": ["admin", "user"]
      },
      "annotations": {
        "inputType": "tel",
        "inputHelperTextBefore": "Enter your phone number with country code (e.g., +84901234567)"
      }
    }
  ]
}

3.6 Annotations cho UI Rendering

Annotations allows customizing how attributes are displayed on registration/account page:

AnnotationDescriptionValue
inputTypeHTML input typetext, email, tel, number, date, select, multiselect, textarea, html5-*
inputHelperTextBeforeHelper text displayed before inputString text
inputHelperTextAfterHelper text displayed after inputString text
inputOptionsFromValidationGet options from validatorValidation name (e.g. "options")

3.7 Progressive Profiling

Progressive profiling allows collecting user information gradually instead of asking for it all upon registration:

  1. Create attribute with Required → Required for user: ON

  2. When the user logs in, if the attribute does not have a value, Keycloak will display a form asking to fill in

  3. Combined with "Enabled when" scopes — only requires attribute when client requests specific scope

For example: Attribute phone_number is only required when the client requests scope phone:

{
  "name": "phone_number",
  "required": {
    "roles": ["user"],
    "scopes": ["phone"]
  }
}

4. Groups and Sub-groups

Groups helps organize users and apply roles and attributes to groups of users at once — instead of assigning individual users.

4.1 Create Group via Admin Console

  1. Click Groups trong sidebar

  2. Click Create group

  3. Enter Name: Engineering

  4. Click Create

4.2 Create Sub-group

Sub-groups inherit attributes and role mappings from parent group:

  1. Click on group Engineering

  2. Click Create sub-group

  3. Enter name: Backend, Frontend, DevOps

Group structure example:

Engineering/
├── Backend/
│   ├── Java Team
│   └── Go Team
├── Frontend/
│   ├── Web Team
│   └── Mobile Team
└── DevOps/
    ├── SRE
    └── Platform

Operations/ ├── HR ├── Finance └── Legal

4.3 Create Group via CLI

# Tạo top-level group
bin/kcadm.sh create groups -r my-company -s name="Engineering"

Lấy group ID

GROUP_ID=$(bin/kcadm.sh get groups -r my-company --fields id,name | jq -r '.[] | select(.name=="Engineering") | .id')

Tạo sub-group

bin/kcadm.sh create groups/$GROUP_ID/children -r my-company -s name="Backend" bin/kcadm.sh create groups/$GROUP_ID/children -r my-company -s name="Frontend" bin/kcadm.sh create groups/$GROUP_ID/children -r my-company -s name="DevOps"

4.4 Group Attributes

Groups can contain key-value attributes — useful for metadata, group configuration:

# Thêm attributes cho group
bin/kcadm.sh update groups/$GROUP_ID -r my-company \
  -s 'attributes={"cost_center":["CC-ENG-001"],"location":["HCM","HN"]}'

Via Admin Console: Click on group → tab Attributes → add key-value pairs.

4.5 Add User to Group

# Qua Admin Console:
# Users → chọn user → tab Groups → Join group → chọn group

Qua CLI

USER_ID=$(bin/kcadm.sh get users -r my-company -q username=john.doe --fields id --format csv --noquotes) bin/kcadm.sh update users/$USER_ID/groups/$GROUP_ID -r my-company -s realm=my-company -s userId=$USER_ID -s groupId=$GROUP_ID -n

Qua REST API

curl -s -X PUT
"http://localhost:8080/admin/realms/my-company/users/$USER_ID/groups/$GROUP_ID"
-H "Authorization: Bearer $ACCESS_TOKEN"
-H "Content-Type: application/json"

4.6 Default Groups

Default groups automatically add new users when creating an account or registering:

  1. Enter Groups

  2. Select the group to set as default

  3. Or go to Realm settings → User registration → Default groups

# Qua CLI
bin/kcadm.sh update realms/my-company -s 'defaultGroups=["/Engineering/Backend"]'

5. Required Actions

Required Actions are actions that the user must perform before being able to log in successfully.

5.1 List of available Required Actions

ActionDescription
Update PasswordRequired password change
Verify EmailVerify email
Configure OTPSet OTP (TOTP/HOTP)
Update ProfileUpdate personal information
Terms and ConditionsAccept terms of use
Configure WebAuthnRegister WebAuthn device
Update User LocaleSelect language
Delete CredentialDelete old credential

5.2 Assign Required Action to User

# Qua Admin Console:
# Users → chọn user → tab Details → Required user actions → chọn actions

Qua CLI

bin/kcadm.sh update users/$USER_ID -r my-company
-s 'requiredActions=["UPDATE_PASSWORD","VERIFY_EMAIL","CONFIGURE_TOTP"]'

Qua REST API

curl -s -X PUT
"http://localhost:8080/admin/realms/my-company/users/$USER_ID"
-H "Authorization: Bearer $ACCESS_TOKEN"
-H "Content-Type: application/json"
-d '{ "requiredActions": ["UPDATE_PASSWORD", "VERIFY_EMAIL"] }'

5.3 Default Required Actions

Configure default required actions for all new users at Authentication → Required actions:

  • Enable column Set as default action for desired action

  • All new users will automatically be assigned default actions

6. User Self-Registration

6.1 Enable Self-Registration

  1. Go to Realm settings → Login

  2. On User registration: ON

  3. The login page will display the "Register" link

6.2 reCAPTCHA cho Registration

To protect registration form from bots, enable reCAPTCHA:

  1. Sign up for Google reCAPTCHA at https://www.google.com/recaptcha

  2. Enter Authentication → Flows → Registration

  3. Find step reCAPTCHA → switch from Disabled to Required

  4. Click gear icon → enter Site Key and Secret Key from Google

6.3 Customize Registration Form

With User Profile, you control which fields are displayed on the registration form:

  • Attributes with Required for user: ON will appear on form

  • Display order according to sort order in User Profile configuration

  • Use attribute groups to group related fields

7. Impersonation

Impersonation allows admins to "fake" login under another user name — useful for debugging and support.

7.1 Using Impersonation

  1. Go to Users → find the user you need to impersonate

  2. Click menu dropdown (kebab menu) → Impersonate

  3. Browser will open a new tab to log in under that user name

  4. All actions recorded in Events with event type IMPERSONATE

7.2 Impersonation qua REST API

curl -s -X POST \
  "http://localhost:8080/admin/realms/my-company/users/$USER_ID/impersonation" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json"

Security note:

  • Only users with role impersonation in realm realm-management can impersonate

  • All impersonation events are logged — important for audit

  • In production, limit impersonation permission to only super admin

8. Search and manage advanced Users

8.1 Search Users

# Tìm theo username
bin/kcadm.sh get users -r my-company -q username=john

Tìm theo email

bin/kcadm.sh get users -r my-company -q email=[email protected]

Tìm theo attribute

bin/kcadm.sh get users -r my-company -q "q=department:Engineering"

Tìm với pagination

bin/kcadm.sh get users -r my-company --offset 0 --limit 20

REST API - tìm với nhiều tiêu chí

curl -s -X GET
"http://localhost:8080/admin/realms/my-company/users?search=john&max=20&first=0"
-H "Authorization: Bearer $ACCESS_TOKEN" | jq '.[].username'

8.2 Delete User

# Qua CLI
bin/kcadm.sh delete users/$USER_ID -r my-company

Qua REST API

curl -s -X DELETE
"http://localhost:8080/admin/realms/my-company/users/$USER_ID"
-H "Authorization: Bearer $ACCESS_TOKEN"

8.3 Disable User (instead of deleting)

# Disable user - vẫn giữ data nhưng không cho login
bin/kcadm.sh update users/$USER_ID -r my-company -s enabled=false

8.4 Bulk Operations

Example script to create multiple users from CSV:

#!/bin/bash
# bulk-create-users.sh

REALM="my-company"

while IFS=',' read -r username email firstName lastName department; do bin/kcadm.sh create users -r $REALM
-s username="$username"
-s email="$email"
-s firstName="$firstName"
-s lastName="$lastName"
-s enabled=true
-s emailVerified=true
-s "attributes={"department":["$department"]}"

bin/kcadm.sh set-password -r $REALM
--username "$username"
--new-password "Welcome@123"
--temporary

echo "Created user: $username" done < users.csv

9. Personal Data Management

Keycloak supports GDPR compliance through Account Console, allowing users:

  • View personal information — email, name, attributes

  • Edit information — depends on permissions in User Profile

  • View sessions — active login sessions

  • Manage devices — view and revoke logged in devices

  • View applications — applications that have been granted access

  • Delete account — manually delete account (if allowed)

Account Console URL:

http://localhost:8080/realms/{realm}/account

Bật tính năng xóa tài khoản:

  1. Vào Authentication → Required actions

  2. Enable action Delete Account

  3. Vào Realm settings → Login → bật Delete account

10. Bài tập thực hành

  1. Tạo User Profile cho realm my-company với các custom attributes:

    • phone_number (required, regex validator cho format quốc tế)
    • department (required, options: Engineering, HR, Finance, Marketing)
    • employee_id (admin-only edit, pattern: EMP-[0-9]{4})
  2. Tạo Group hierarchy:

    • Engineering → Backend, Frontend, DevOps
    • Operations → HR, Finance
  3. Tạo 5 users qua CLI, mỗi user thuộc một group khác nhau, password tạm thời

  4. Bật self-registration với verify email và test đăng ký

  5. Cấu hình password policy: min 10 chars, 1 uppercase, 1 digit, 1 special, history 5, expire 90 days

11. Tổng kết

Trong bài này, bạn đã học:

  • Tạo và quản lý Users qua Admin Console, CLI, và REST API

  • Thiết lập Credentials và Password Policies

  • Sử dụng User Profile để định nghĩa attribute schema với validators và annotations

  • Tạo Groups và sub-groups với hierarchy, attributes, và default groups

  • Cấu hình Required Actions bắt buộc cho users

  • Bật Self-Registration với reCAPTCHA

  • Sử dụng Impersonation cho debugging

  • Quản lý Personal Data cho GDPR compliance

Bài tiếp theo sẽ hướng dẫn về Roles, Permissions và Access Control trong Keycloak.