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

Lesson 3: Admin Console and creating the first Realm

Get acquainted with the Admin Console, create the first admin user, create and configure Realm, Realm Settings (General, Login, Email, Themes, Localization, Keys, Security Defenses), Admin CLI (kcadm.sh) and basic Admin REST API.

🔒 DevSecOps — Lesson 3 Lesson 3: Admin Console and creating the first Realm

Keycloak from Basic to Advanced

Part 1: Keycloak Platform

xdev.asia

1. Access Admin Console

After installing Keycloak (standalone or Docker), you can access Admin Console — the centralized administration interface for the entire Keycloak system.

Access URL

By default, Admin Console is located at:

http://localhost:8080/admin

Nếu bạn chạy Keycloak bằng Docker với port mapping khác:

http://localhost:<PORT>/admin

Tạo Admin User đầu tiên

Khi lần đầu truy cập Keycloak, bạn cần tạo initial admin user để đăng nhập vào Admin Console. Có hai cách:

Cách 1: Qua biến môi trường (khuyến nghị cho Docker/Production)

docker run -d --name keycloak \
  -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
  -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
  -p 8080:8080 \
  quay.io/keycloak/keycloak:26.2.4 start-dev

Method 2: Via welcome page (only when accessing from localhost)

Visit http://localhost:8080, and you will see the admin user creation form. Enter username and password, then click Create.

Method 3: Via command line

# Standalone
export KC_BOOTSTRAP_ADMIN_USERNAME=admin
export KC_BOOTSTRAP_ADMIN_PASSWORD=admin
bin/kc.sh start-dev

Admin Console interface

After logging in, you will see the Admin Console interface with the main components:

  • Realm selector (upper left corner) — select the currently managed realm

  • Left sidebar — main navigation menu: Clients, Client scopes, Realm roles, Users, Groups, Sessions, Events, Realm settings, Authentication, Identity providers, User federation

  • Main content area — displays detailed content of the selected item

  • User dropdown (upper right corner) — admin account management, sign out

2. Create first Realm

Master Realm vs Custom Realm

When installing Keycloak, a realm named master is created. Master realm is a special realm used to manage other realms — should not use master realm for application.

Best practices:

  • Use master realm only for super admin to manage Keycloak system

  • Create a separate custom realm for each organization, project, or environment

  • Give a meaningful realm name: mycompany-dev, mycompany-staging, mycompany-prod

Create Realm via Admin Console

  1. Click on realm selector (dropdown in the upper left corner, showing "master")

  2. Click Create realm

  3. Enter information:

    • Realm name: my-company (contains only lowercase, numbers, hyphens)
    • Enabled: ON
  4. Click Create

Create Realm from JSON file

You can import realm from a JSON file — useful for replicating configuration between environments:

{
  "realm": "my-company",
  "enabled": true,
  "displayName": "My Company",
  "displayNameHtml": "<strong>My Company</strong>",
  "sslRequired": "external",
  "registrationAllowed": false,
  "loginWithEmailAllowed": true,
  "duplicateEmailsAllowed": false,
  "resetPasswordAllowed": true,
  "editUsernameAllowed": false,
  "bruteForceProtected": true,
  "permanentLockout": false,
  "maxFailureWaitSeconds": 900,
  "minimumQuickLoginWaitSeconds": 60,
  "waitIncrementSeconds": 60,
  "quickLoginCheckMilliSeconds": 1000,
  "maxDeltaTimeSeconds": 43200,
  "failureFactor": 5,
  "defaultSignatureAlgorithm": "RS256",
  "accessTokenLifespan": 300,
  "ssoSessionIdleTimeout": 1800,
  "ssoSessionMaxLifespan": 36000
}

Import via Admin Console: when creating realm, click Browse to select JSON file.

3. Realm Settings details

After creating the realm, access Realm settings from the sidebar for detailed configuration.

3.1 Tab General

SettingDescriptionRecommended value
Display nameName displayed on login pageCompany/project name
HTML display nameHTML support for display nameLogo + name
Frontend URLThe URL the client uses to connecthttps://auth.mycompany.com
Require SSLRequire SSL for requestsexternal (dev) / all (prod)
User-managed accessAllow users to manage resources (UMA)OFF (unless UMA is needed)
ACR to LoA mappingMapping Authentication Context Class ReferenceConfigure when step-up auth is needed

3.2 Tab Login

Configure the behavior of the login page:

SettingDescriptionDefault
User registrationAllow new account registrationOFF
Forgot passwordShow link "Forgot password"OFF
Remember meCheckbox "Remember me"OFF
Email as usernameUse email as usernameOFF
Login with emailAllow login with emailON
Duplicate emailsAllow duplicate emailsOFF
Verify emailRequired email verificationOFF
Edit usernameAllow to change usernameOFF

Recommended for production:

User registration: OFF (hoặc ON với reCAPTCHA)
Forgot password: ON
Remember me: ON
Email as username: Tùy yêu cầu
Login with email: ON
Verify email: ON
Edit username: OFF

3.3 Tab Email

Configure SMTP server to send email (verification, reset password, notifications):

SettingDescription
FromOutgoing email address (e.g. [email protected])
From display nameEmail display name
Reply toReply address (eg [email protected])
HostSMTP server hostname
PortSMTP port (587 cho STARTTLS, 465 cho SSL)
EncryptionEnable SSL or STARTTLS
AuthenticationUsername and password for SMTP

Configuration example with Gmail SMTP:

Host: smtp.gmail.com
Port: 587
From: [email protected]
Enable StartTLS: ON
Authentication: ON
Username: [email protected]
Password: app-specific-password

3.4 Tab Themes

Customize interface for different pages:

  • Login theme — login, registration, password reset page

  • Account theme — account management page for users

  • Admin console theme — Admin Console theme

  • Email theme — template cho emails

Keycloak provides the theme keycloak (default) and keycloak.v2 (Account Console v3, React-based). You can create custom themes — which will be discussed in the next article.

3.5 Tab Localization

Multilingual support for login, account, email pages:

  1. Turn on Internationalization: ON

  2. Select Supported locales: en, vi, ja, zh-CN,...

  3. Select Default locale: vi (for default Vietnamese interface)

  4. Customize message bundles for each locale if needed

3.6 Tab Keys

Manage cryptographic keys for realm — used to sign and encrypt tokens:

  • Active keys — keys being used to sign tokens

  • Passive keys — old keys still used to verify previously signed tokens

  • Disabled keys — keys are no longer in use

Default key providers:

ProviderAlgorithmPurpose
rsa-generatedRS256Sign JWT tokens
rsa-enc-generatedRSA-OAEPEncrypt tokens
hmac-generatedHS512HMAC signing
aes-generatedAESSymmetric encryption
ecdsa-generatedES256Elliptic curve signing

Key rotation: Add new key provider → new key becomes active → old key turns passive → after a while, disable old key.

3.7 Tab Tokens

Configure lifetime and behavior of tokens:

SettingDescriptionRecommended value
Default Signature AlgorithmJWT Signature AlgorithmRS256
Revoke Refresh TokenRevoke refresh token after useON (production)
SSO Session IdleMaximum session idle time30 minutes
SSO Session MaxMax session time10 hours
Access Token LifespanAccess Token Lifespan5 minutes
Client login timeoutMaximum time for login flow5 minutes

3.8 Tab Security Defenses

Security configuration for realm:

Headers:

HeaderDefault valueDescription
X-Frame-OptionsSAMEORIGINAnti-clickjacking
Content-Security-Policyframe-src 'self'; ...CSP header
X-Content-Type-OptionsnosniffAnti-MIME sniffing
X-XSS-Protection1; mode=blockXSS filter
Strict-Transport-Securitymax-age=31536000HTTPS Required
Referrer-Policyno-referrerReferrer header control

Brute Force Detection:

  • Enabled: ON (turn on anti-brute force)

  • Permanent lockout: OFF (automatically unlocks after time)

  • Max login failures: 5 (after 5 failed login attempts will be locked)

  • Wait increment: 60 seconds (incremental waiting time)

  • Max wait: 900 seconds (maximum waiting time 15 minutes)

  • Quick login check: 1000 ms (detected login too fast)

4. Admin CLI (kcadm.sh)

Keycloak provides Admin CLI (kcadm.sh) — a command-line tool to administer Keycloak without accessing the Admin Console.

4.1 Configure Credentials

Before using Admin CLI, you need to log in:

# Đăng nhập vào Keycloak server
bin/kcadm.sh config credentials \
  --server http://localhost:8080 \
  --realm master \
  --user admin \
  --password admin

Với Docker

docker exec -it keycloak /opt/keycloak/bin/kcadm.sh config credentials
--server http://localhost:8080
--realm master
--user admin
--password admin

Security note: In production, use --client and --secret instead of username/password directly on the command line.

4.2 Realm Management with CLI

Create new realm:

# Tạo realm cơ bản
bin/kcadm.sh create realms \
  -s realm=my-company \
  -s enabled=true \
  -s displayName="My Company"

Tạo realm với nhiều cấu hình

bin/kcadm.sh create realms
-s realm=my-company
-s enabled=true
-s displayName="My Company"
-s registrationAllowed=false
-s loginWithEmailAllowed=true
-s resetPasswordAllowed=true
-s sslRequired=external
-s bruteForceProtected=true

See list of realms:

# Lấy tất cả realms
bin/kcadm.sh get realms --fields realm,enabled,displayName

Output:

[ {

"realm" : "master",

"displayName" : "Keycloak",

"enabled" : true

}, {

"realm" : "my-company",

"displayName" : "My Company",

"enabled" : true

} ]

View details realm:

bin/kcadm.sh get realms/my-company

Cập nhật realm:

bin/kcadm.sh update realms/my-company \
  -s displayName="My Company Production" \
  -s sslRequired=all \
  -s bruteForceProtected=true \
  -s failureFactor=5

Delete realm:

bin/kcadm.sh delete realms/my-company

4.3 Cấu hình Realm Settings với CLI

Cấu hình Login settings:

bin/kcadm.sh update realms/my-company \
  -s registrationAllowed=true \
  -s resetPasswordAllowed=true \
  -s rememberMe=true \
  -s verifyEmail=true \
  -s loginWithEmailAllowed=true \
  -s duplicateEmailsAllowed=false

Token settings:

bin/kcadm.sh update realms/my-company \
  -s accessTokenLifespan=300 \
  -s ssoSessionIdleTimeout=1800 \
  -s ssoSessionMaxLifespan=36000 \
  -s revokeRefreshToken=true \
  -s refreshTokenMaxReuse=0

Configure SMTP Email:

bin/kcadm.sh update realms/my-company \
  -s 'smtpServer={"host":"smtp.gmail.com","port":"587","from":"[email protected]","fromDisplayName":"My Company","starttls":"true","auth":"true","user":"[email protected]","password":"app-password"}'

Export realm configuration:

# Export realm sang file JSON
bin/kcadm.sh get realms/my-company > my-company-realm.json

5. Admin REST API

Keycloak provides Admin REST API allowing full administration via HTTP requests — great for automation, CI/CD, and integration with other systems.

5.1 Get Access Token

Before calling the API, need to get access token from master realm:

# Lấy access token bằng admin credentials
ACCESS_TOKEN=$(curl -s -X POST \
  "http://localhost:8080/realms/master/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=admin" \
  -d "password=admin" \
  -d "grant_type=password" \
  -d "client_id=admin-cli" | jq -r '.access_token')

echo $ACCESS_TOKEN

5.2 Realm Management with API

Get list of realms:

curl -s -X GET \
  "http://localhost:8080/admin/realms" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" | jq '.[].realm'

Create new realm:

curl -s -X POST \
  "http://localhost:8080/admin/realms" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "realm": "my-company",
    "enabled": true,
    "displayName": "My Company",
    "sslRequired": "external",
    "registrationAllowed": false,
    "loginWithEmailAllowed": true,
    "resetPasswordAllowed": true,
    "bruteForceProtected": true,
    "failureFactor": 5
  }'

Get realm details:

curl -s -X GET \
  "http://localhost:8080/admin/realms/my-company" \
  -H "Authorization: Bearer $ACCESS_TOKEN" | jq .

Update realm:

curl -s -X PUT \
  "http://localhost:8080/admin/realms/my-company" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "displayName": "My Company Updated",
    "sslRequired": "all"
  }'

Delete realm:

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

5.3 Important API Endpoints

EndpointMethodDescription
/admin/realmsGETRealms List
/admin/realmsPOSTCreate new realm
/admin/realms/{realm}GETDetails realm
/admin/realms/{realm}PUTUpdate realm
/admin/realms/{realm}DELETEDelete realm
/admin/realms/{realm}/usersGETList of users
/admin/realms/{realm}/usersPOSTCreate user
/admin/realms/{realm}/clientsGETList of clients
/admin/realms/{realm}/rolesGETList of realm roles
/admin/realms/{realm}/groupsGETList of groups
/admin/realms/{realm}/eventsGETEvents log

5.4 Using Postman

Keycloak provides OpenAPI spec for Admin REST API. You can import into Postman or Swagger UI to easily explore and test the API:

# OpenAPI spec URL
http://localhost:8080/admin/realms/{realm}/.well-known/openid-configuration

6. Practice exercises

Do the following exercises to consolidate knowledge:

  1. Create realm "dev-company" via Admin Console with settings:

    • Display name: "Dev Company"
    • Login with email: ON
    • User registration: ON
    • Forgot password: ON
    • Verify email: ON
    • Remember me: ON
  2. Configure Brute Force Detection for the newly created realm:

    • Max login failures: 3
    • Wait increment: 120 seconds
    • Max wait: 600 seconds
  3. Use kcadm.sh to create realm "staging-company" with similar configuration

  4. Use Admin REST API (curl) to create realm "test-company" and verify by getting list of realms

  5. Export realm "dev-company" to JSON and re-import with a different name

7. Summary

In this lesson, you learned:

  • How to access and use Admin Console

  • Create the first admin user through multiple methods

  • Create and configure Realm — key management unit in Keycloak

  • Understand important Realm Settings: General, Login, Email, Themes, Localization, Keys, Tokens, Security Defenses

  • Use Admin CLI (kcadm.sh) to administer via command line

  • Use Admin REST API to automate administration

The next article will provide detailed instructions on managing Users, Groups and User Profile in Keycloak.