
Keycloak Administration
- 248 installs
- 14 repo stars
- Updated January 23, 2026
- dauquangthanh/hanoi-rainbow
For development and infrastructure management.
About
keycloak-administration is an AI coding tool that enhances development workflows. Builders use it for infrastructure, integration, and platform development within the catalog ecosystem.
- keycloak-administration
- Development
Keycloak Administration by the numbers
- 248 all-time installs (skills.sh)
- Ranked #1,525 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/dauquangthanh/hanoi-rainbow --skill keycloak-administrationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 248 |
|---|---|
| repo stars | ★ 14 |
| Last updated | January 23, 2026 |
| Repository | dauquangthanh/hanoi-rainbow ↗ |
What it does
For development and infrastructure management.
Files
KeyCloak Administration
Overview
Provides systematic KeyCloak administration guidance covering installation, configuration, realm management, security hardening, and operational best practices. Supports both standalone and clustered deployments for secure, scalable identity and access management (IAM) solutions.
Quick Start Guide
Choose your task and load the appropriate reference:
1. New Installation → Continue to Installation & Setup 2. Realm & User Management → Load realm-management.md 3. Client Configuration → Load client-configuration.md 4. Authentication & SSO → Load authentication-sso.md 5. Authorization & RBAC → Load authorization-rbac.md 6. User Federation (LDAP/AD) → Load user-federation.md 7. Security Hardening → Load security-hardening.md 8. High Availability & Scaling → Load ha-scalability.md 9. Troubleshooting → Load troubleshooting.md 10. Integration Examples → Load integration-examples.md
Installation & Setup
Deployment Options
1. Standalone Mode (Development/Testing)
# Download and start KeyCloak
wget https://github.com/keycloak/keycloak/releases/download/[VERSION]/keycloak-[VERSION].tar.gz
tar -xvzf keycloak-[VERSION].tar.gz
cd keycloak-[VERSION]
bin/kc.sh start-dev
# Access: http://localhost:8080
# Create initial admin user on first access2. Production Mode with Database
# Configure and build
bin/kc.sh build --db=postgres
# Set environment variables
export KC_DB=postgres
export KC_DB_URL=jdbc:postgresql://localhost/keycloak
export KC_DB_USERNAME=keycloak
export KC_DB_PASSWORD=password
export KC_HOSTNAME=keycloak.example.com
# Start production mode
bin/kc.sh start --optimized3. Docker Deployment
docker run -d \
--name keycloak \
-p 8080:8080 \
-e KEYCLOAK_ADMIN=admin \
-e KEYCLOAK_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:latest \
start-dev4. Kubernetes - Use KeyCloak Operator or Helm charts
Initial Configuration Steps
1. Admin Account: Create on first access with strong password (12+ chars) 2. Hostname: Configure KC_HOSTNAME for production 3. SSL/TLS: Set up certificates (required for production) 4. Database: Configure PostgreSQL connection 5. Email: Configure SMTP for notifications
# Email settings
KC_SMTP_HOST=smtp.example.com
KC_SMTP_PORT=587
KC_SMTP_FROM=noreply@example.com
KC_SMTP_STARTTLS=trueCore Concepts
Realms
- Master realm: Administrative realm (don't use for apps)
- Application realms: Separate realms per app/environment
- Create: Admin Console → Create Realm
Users & Groups
- Users: Individual accounts with credentials
- Groups: Organize users hierarchically
- Attributes: Custom key-value pairs
- Federation: Sync from LDAP/AD (see user-federation.md)
Clients
- OIDC clients: Modern OAuth 2.0/OIDC applications
- SAML clients: Legacy enterprise applications
- Types: Confidential (server-side) or Public (SPA/mobile)
- Details: See client-configuration.md
Roles & Permissions
- Realm roles: Global across all clients
- Client roles: Specific to one client
- Composite roles: Inherit multiple roles
- Details: See authorization-rbac.md
Common Tasks
Configure SSO for Applications
1. Create OIDC client for your application 2. Set redirect URIs (exact URLs, no wildcards) 3. Configure client type:
- Confidential: Server-side apps (need client secret)
- Public: SPAs/mobile apps (use PKCE)
4. Obtain configuration from realm endpoint:
https://keycloak.example.com/realms/{realm}/.well-known/openid-configuration5. Integrate with your app (see integration-examples.md)
Enable Multi-Factor Authentication
1. Authentication → Flows 2. Duplicate Browser flow 3. Add OTP or WebAuthn authenticator 4. Set as Required or Conditional 5. Bind to realm 6. Users configure MFA on next login
Details: See authentication-sso.md
Connect to LDAP/Active Directory
1. User Federation → Add LDAP Provider 2. Configure connection (URL, bind DN, credentials) 3. Set search base: ou=users,dc=example,dc=com 4. Configure mappers for attributes 5. Test connection and sync users
Details: See user-federation.md
Secure Production Deployment
Essential security measures:
- SSL/TLS: Required for all production traffic
- Password policy: 12+ chars, complexity requirements
- Brute force protection: Enable with lockout
- Token lifespans: Short access tokens (5-15 min)
- Admin MFA: Enable for all admin accounts
- Event logging: Monitor authentication events
Complete checklist: See security-hardening.md
Set Up High Availability
1. Shared database: PostgreSQL/MySQL for all nodes 2. Distributed caching: Configure Infinispan 3. Load balancer: HAProxy/NGINX with sticky sessions 4. Health checks: Use /health/ready and /health/live 5. Monitoring: Prometheus metrics at /metrics
Details: See ha-scalability.md
Troubleshooting Quick Reference
Users Can't Login
- Check user enabled status
- Verify redirect URIs match exactly
- Review required actions
- Check Events → Login Events
Token Validation Fails
- Verify realm public key
- Check token expiration
- Validate issuer URL
- Confirm audience claim
LDAP Sync Issues
- Test LDAP connection
- Verify bind credentials
- Check user DN path
- Run manual sync
Full troubleshooting guide: See troubleshooting.md
Essential Commands
# Start modes
bin/kc.sh start-dev # Development
bin/kc.sh start --optimized # Production
# Build for database
bin/kc.sh build --db=postgres
# Export/Import realm
bin/kc.sh export --dir /backup --realm my-realm
bin/kc.sh import --dir /backup
# Admin CLI
bin/kcadm.sh config credentials --server http://localhost:8080 --realm master --user admin
bin/kcadm.sh create realms -s realm=my-realm -s enabled=true
bin/kcadm.sh create users -r my-realm -s username=john -s enabled=true
bin/kcadm.sh set-password -r my-realm --username john --new-password secretBest Practices Summary
Architecture
- Separate realms per application/environment
- Use groups for structure, roles for permissions
- Plan token lifespans based on security needs
- Enable session replication in clusters
Security
- Always use SSL/TLS in production
- Enable MFA for privileged accounts
- Implement brute force protection
- Regular security audits
- Principle of least privilege
Operations
- Automate backups and test restores
- Monitor metrics and set alerts
- Document configurations
- Regular updates and patching
- Capacity planning
Development
- Use PKCE for public clients
- Implement proper token refresh
- Handle token expiration gracefully
- Validate tokens correctly
- Use appropriate grant types
Reference Documentation
For detailed guidance, load the appropriate reference file:
- [realm-management.md](references/realm-management.md) - Realm configuration, users, groups
- [client-configuration.md](references/client-configuration.md) - OIDC/SAML clients, scopes, mappers
- [authentication-sso.md](references/authentication-sso.md) - Auth flows, MFA, social login, IdP
- [authorization-rbac.md](references/authorization-rbac.md) - Roles, permissions, fine-grained auth
- [user-federation.md](references/user-federation.md) - LDAP/AD integration, custom providers
- [security-hardening.md](references/security-hardening.md) - Security policies, monitoring, auditing
- [ha-scalability.md](references/ha-scalability.md) - Clustering, performance, backup, DR
- [troubleshooting.md](references/troubleshooting.md) - Common issues, logging, diagnostics
- [integration-examples.md](references/integration-examples.md) - Spring Boot, Node.js, React, Python, Docker, K8s
Additional Resources
- Official documentation: <https://www.keycloak.org/documentation>
- Admin CLI reference for automation
- Client adapter docs for frameworks
- Community forums for support
Authentication & Single Sign-On (SSO)
Authentication Flows
Browser Flow (default login)
1. Cookie check 2. Kerberos (if configured) 3. Identity Provider redirector 4. Username/password form 5. OTP (if MFA enabled) 6. WebAuthn (if configured)
Direct Grant Flow (API login)
1. Username/password validation 2. OTP validation (if required) 3. Conditional OTP
Registration Flow
1. Profile validation 2. Password validation 3. reCAPTCHA (if configured) 4. Terms and conditions
Customizing Flows
1. Authentication → Flows 2. Duplicate existing flow (don't modify built-in flows) 3. Add/remove/reorder authenticators 4. Set requirements: Required, Alternative, Disabled, Conditional 5. Bind custom flow to realm (Browser Flow, Direct Grant Flow, etc.)
Multi-Factor Authentication (MFA)
OTP (Time-based)
1. Authentication → Required Actions → Enable "Configure OTP" 2. Users configure with authenticator apps (Google Authenticator, Authy) 3. Recovery codes: Generate backup codes
WebAuthn (FIDO2)
1. Enable WebAuthn authenticators in authentication flow 2. Users register hardware keys or biometrics 3. Passwordless authentication option
Conditional MFA
- Configure "Conditional OTP" in authentication flow
- Set conditions: IP ranges, user attributes, authentication age
Single Sign-On (SSO)
OIDC SSO Configuration
1. Configure OIDC client for each application 2. Set valid redirect URIs 3. Applications share SSO session via cookies 4. Configure session timeouts appropriately
SAML SSO Configuration
1. Create SAML client 2. Download/provide SAML metadata 3. Configure assertion consumer service URL 4. Set up attribute mappings 5. Configure name ID format (email, username, persistent)
SSO Session Management
- SSO Session Idle: Extend on activity
- SSO Session Max: Absolute limit
- Remember Me: Long-lived sessions
- Single Logout: Centralized logout across applications
Identity Brokering
Purpose: Allow users to login with external identity providers
Configure Identity Provider
1. Identity Providers → Add provider (Google, Facebook, OIDC, SAML) 2. Set client ID and secret (from provider) 3. Configure scopes and claim mappings 4. Set default scopes: openid profile email
Common Providers
Google:
- Client ID and Secret from Google Cloud Console
- Authorized redirect URI:
https://keycloak.example.com/realms/[realm]/broker/google/endpoint
Azure AD (OIDC):
- Register application in Azure AD
- Set redirect URI
- Configure groups/claims
SAML Identity Provider:
- Import SAML metadata from provider
- Configure attribute mappings
- Set name ID format
Identity Provider Mappers
- Map external claims to KeyCloak user attributes
- Attribute importer: Import specific claims
- Hardcoded attribute: Set fixed values for users from this IdP
- Username template: Define username format
Social Login
Supported Providers
Google, Facebook, GitHub, LinkedIn, Twitter, Microsoft, Apple, Instagram, PayPal, Stack Overflow
Configuration Steps
1. Create OAuth application with provider 2. Set callback URL: https://keycloak.example.com/realms/[realm]/broker/[provider]/endpoint 3. Copy client ID and secret to KeyCloak 4. Configure scopes (typically openid profile email) 5. Enable on login screen
Authorization & Role-Based Access Control (RBAC)
Roles
Realm Roles
- Global roles across all clients in realm
- Example:
admin,user,manager
Client Roles
- Specific to individual clients
- Example:
app-admin,app-viewer
Creating Roles
1. Realm Settings → Roles → Create Role 2. Set role name and description 3. Add composite roles (role inherits other roles)
Composite Roles
- Aggregate multiple roles into one
- Example:
adminrole includesuserandmanagerroles - Simplifies role assignment
Default Roles
- Automatically assigned to new users
- Set in Realm Settings → Roles → Default Roles
Role Mapping
Assign Roles to Users
1. Users → Select user → Role Mappings 2. Assign realm roles and/or client roles 3. View effective roles (includes inherited roles)
Assign Roles to Groups
1. Groups → Select group → Role Mappings 2. All group members inherit these roles 3. Preferred method for scalable access control
Fine-Grained Authorization (UMA)
Purpose: Resource-level authorization with policies
Enable Authorization
1. Client → Authorization tab → Enable 2. Define resources, scopes, and policies 3. Evaluate permissions at runtime
Authorization Components
Resources: Protected objects (e.g., /api/documents, document-123)
Scopes: Actions on resources (e.g., read, write, delete)
Policies: Rules defining access (role-based, time-based, user-based, JavaScript)
Permissions: Connect resources/scopes to policies
Policy Types
- Role policy: Based on realm/client roles
- User policy: Specific users
- Group policy: Group membership
- Time policy: Date/time restrictions
- JavaScript policy: Custom logic
- Aggregated policy: Combine multiple policies
Example Authorization Flow
1. Define resource: /api/documents/{id} 2. Define scopes: read, write, delete 3. Create policy: "Only document owners can delete" 4. Create permission: Connect delete scope to policy 5. Application enforces by querying KeyCloak authorization endpoint
Authorization Best Practices
- Use realm roles for global permissions
- Use client roles for application-specific permissions
- Assign roles to groups, not individual users
- Use composite roles to simplify management
- Implement fine-grained authorization for complex requirements
- Document role hierarchies and permissions
- Regular role audits and cleanup
Client Configuration
Client Types
1. OpenID Connect (OIDC) Clients
- Standard flow: Authorization code flow (web applications)
- Implicit flow: Legacy, not recommended
- Direct access grants: Resource owner password credentials (use sparingly)
- Service accounts: Client credentials for machine-to-machine
2. SAML Clients
- SAML 2.0 protocol
- For legacy enterprise applications
- Supports SSO and SLO (Single Logout)
Creating OIDC Clients
Standard Web Application
1. Clients → Create Client 2. Client type: OpenID Connect 3. Client ID: Unique identifier (e.g., my-app) 4. Client protocol: openid-connect
Configuration:
- Root URL: Base application URL
- Valid redirect URIs: Allowed callback URLs (e.g.,
https://app.example.com/callback,http://localhost:3000/callback) - Valid post logout redirect URIs: Allowed logout callbacks
- Web origins: CORS allowed origins (e.g.,
https://app.example.com) - Admin URL: For backchannel communication
Access Settings:
- Standard flow: Enable for authorization code flow
- Direct access grants: Enable for password grant (caution)
- Implicit flow: Disable (deprecated)
- Service accounts: Enable for client credentials flow
Authentication Flow:
- Client authentication: On (confidential) or Off (public)
- Client authenticator: Client secret, JWT, or X509 certificate
Advanced Settings:
- Access token lifespan: Override realm default if needed
- Proof Key for Code Exchange (PKCE): Required for public clients
- OAuth 2.0 Device Authorization Grant: For limited-input devices
Service Account Clients
For machine-to-machine authentication:
1. Create client with service accounts enabled 2. Disable standard/implicit flows 3. Assign service account roles in "Service Account Roles" tab 4. Use client_credentials grant type
Client Scopes
Purpose: Control what information tokens contain
Default Scopes:
- openid: Required for OIDC
- profile: User profile information
- email: Email address
- address: Physical address
- phone: Phone number
- roles: User roles
- web-origins: CORS origins
Custom Scopes:
1. Client Scopes → Create 2. Add protocol mappers for custom claims 3. Assign to clients (default or optional)
Protocol Mappers
- User attribute: Map user attributes to token claims
- User property: Map username, email, etc.
- Group membership: Include user groups
- Hardcoded claim: Static values
- Audience: Add audience claims
Client Security Best Practices
Confidential Clients
- Client authentication: ON
- Use client secrets or client certificates
- Rotate client secrets periodically
- Store secrets securely (vault, environment variables)
Public Clients
- Client authentication: OFF
- Require PKCE (Proof Key for Code Exchange)
- Restrict redirect URIs strictly
- Set valid web origins for CORS
Redirect URI Validation
- Use exact URLs (no wildcards in production)
- Avoid
localhostin production configurations - Never use
*wildcard - Use HTTPS only (except localhost development)
High Availability & Scalability
Clustering
Configure Cluster
1. Use shared database (PostgreSQL, MySQL) 2. Enable distributed cache (Infinispan) 3. Configure cluster nodes in cache-ispn.xml 4. Set up load balancer (HAProxy, NGINX, AWS ALB)
Cluster Requirements
- Shared database for persistent data
- Multicast or TCP discovery for cluster formation
- Session replication across nodes
- Consistent configuration across all nodes
Load Balancer Configuration
- Sticky sessions: Recommended for performance
- Health checks:
/healthendpoint - SSL termination: At load balancer or KeyCloak
- Connection timeouts: 60+ seconds for admin operations
Database Performance
Connection Pool Settings
# Increase pool size for high load
KC_DB_POOL_INITIAL_SIZE=10
KC_DB_POOL_MIN_SIZE=10
KC_DB_POOL_MAX_SIZE=50Database Optimization
- Index on username, email columns
- Regular vacuum (PostgreSQL)
- Monitor slow queries
- Use connection pooling (HikariCP built-in)
- Database replication for read scaling
Caching Strategy
Cache Types
- Realm cache: Realm configuration
- User cache: User data from user federation
- Keys cache: Signing and encryption keys
- Authorization cache: Permissions and policies
Cache Configuration
- Max entries: Limit memory usage
- Lifespan: Balance freshness vs performance
- Eviction policy: LRU (Least Recently Used)
- Invalidation: Distributed in clustered environments
Monitoring
Health Checks
- Liveness:
/health/live(is KeyCloak running) - Readiness:
/health/ready(is KeyCloak ready to serve requests)
Metrics
- Enable metrics endpoint:
/metrics - Integrate with Prometheus/Grafana
- Monitor:
- Active sessions
- Token issuance rate
- Login success/failure rate
- Database connection pool usage
- Cache hit/miss ratio
- JVM memory and GC
Alerting
- High failed login rate
- Database connection pool exhaustion
- High JVM memory usage
- Increased response times
- SSL certificate expiration
Backup & Disaster Recovery
Backup Strategy
Database Backup:
- Regular automated backups (daily minimum)
- Point-in-time recovery capability
- Off-site backup storage
- Test restore procedures regularly
Configuration Backup:
- Export realm configurations periodically
- Version control for realm exports
- Document custom configurations
- Backup custom themes and extensions
Export Realm:
# Export single realm
bin/kc.sh export --dir /backup --realm {realm-name}
# Export all realms
bin/kc.sh export --dir /backup
# Export with users (careful: large file)
bin/kc.sh export --dir /backup --realm {realm-name} --users realm_fileDisaster Recovery
Recovery Steps:
1. Restore database from backup 2. Deploy KeyCloak with same version 3. Import realm configurations 4. Verify DNS and SSL certificates 5. Test authentication flows 6. Validate client integrations
Recovery Time Objective (RTO):
- Target: < 4 hours for production
- Keep documentation updated
- Maintain runbooks for recovery procedures
- Regular DR testing (quarterly)
Migration & Upgrades
Version Upgrades
Pre-Upgrade Checklist:
- [ ] Backup database
- [ ] Export realm configurations
- [ ] Review release notes for breaking changes
- [ ] Test upgrade in non-production environment
- [ ] Plan rollback procedure
- [ ] Schedule maintenance window
Upgrade Process:
1. Stop KeyCloak service 2. Backup database 3. Deploy new KeyCloak version 4. Run database migration (automatic on startup) 5. Start KeyCloak 6. Verify functionality 7. Monitor logs for errors
Rollback Plan:
- Keep previous version binaries
- Restore database backup
- Redeploy previous version
- Document rollback decision
Migration from Other Systems
From Legacy IAM (e.g., proprietary systems):
1. Export users and groups (CSV, LDAP, API) 2. Map roles and permissions 3. Import users via Admin API or User Federation 4. Migrate client configurations manually 5. Update applications to use KeyCloak 6. Run parallel for testing period 7. Cutover and decommission legacy system
From Other OAuth/OIDC Providers:
1. Export client configurations 2. Recreate clients in KeyCloak 3. Update application endpoints 4. Migrate user database or use federation 5. Test authentication flows 6. Gradual cutover by application
Performance Best Practices
- Use database connection pooling
- Enable caching for realm and user data
- Configure distributed caching in clustered setups
- Monitor and tune JVM settings
- Use sticky sessions with load balancers
- Implement CDN for static resources
- Regular database maintenance (vacuum, analyze)
- Monitor and optimize slow queries
- Scale horizontally for high load
- Use persistent sessions for stateful applications
Integration Examples
Spring Boot Integration
Maven Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>Application Configuration
# application.yml
spring:
security:
oauth2:
client:
registration:
keycloak:
client-id: spring-app
client-secret: {client-secret}
authorization-grant-type: authorization_code
scope: openid, profile, email
provider:
keycloak:
issuer-uri: https://keycloak.example.com/realms/my-realmSecurity Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.oauth2Login()
.and()
.oauth2ResourceServer().jwt();
return http.build();
}
}Node.js/Express Integration
Installation
npm install keycloak-connect express-sessionConfiguration
const Keycloak = require('keycloak-connect');
const session = require('express-session');
const memoryStore = new session.MemoryStore();
app.use(session({
secret: 'some-secret',
resave: false,
saveUninitialized: true,
store: memoryStore
}));
const keycloak = new Keycloak({
store: memoryStore
}, {
realm: 'my-realm',
'auth-server-url': 'https://keycloak.example.com/',
'ssl-required': 'external',
resource: 'node-app',
credentials: {
secret: 'client-secret'
}
});
app.use(keycloak.middleware());
// Protected route
app.get('/protected', keycloak.protect(), (req, res) => {
res.send('Protected resource');
});
// Role-based protection
app.get('/admin', keycloak.protect('admin'), (req, res) => {
res.send('Admin resource');
});React/SPA Integration
Installation
npm install keycloak-jsConfiguration
import Keycloak from 'keycloak-js';
const keycloak = new Keycloak({
url: 'https://keycloak.example.com/',
realm: 'my-realm',
clientId: 'react-app'
});
keycloak.init({
onLoad: 'login-required',
checkLoginIframe: false,
pkceMethod: 'S256'
}).then(authenticated => {
if (authenticated) {
console.log('Access Token:', keycloak.token);
console.log('User Info:', keycloak.tokenParsed);
// Refresh token before expiration
setInterval(() => {
keycloak.updateToken(70).then((refreshed) => {
if (refreshed) {
console.log('Token refreshed');
}
}).catch(() => {
console.log('Failed to refresh token');
});
}, 60000);
} else {
console.log('Not authenticated');
}
}).catch(() => {
console.log('Failed to initialize');
});API Calls with Token
const fetchData = async () => {
const response = await fetch('https://api.example.com/data', {
headers: {
'Authorization': `Bearer ${keycloak.token}`
}
});
return response.json();
};Python/Flask Integration
Installation
pip install flask-oidcConfiguration
from flask import Flask, g
from flask_oidc import OpenIDConnect
app = Flask(__name__)
app.config.update({
'SECRET_KEY': 'your-secret-key',
'OIDC_CLIENT_SECRETS': 'client_secrets.json',
'OIDC_ID_TOKEN_COOKIE_SECURE': False,
'OIDC_REQUIRE_VERIFIED_EMAIL': False,
'OIDC_OPENID_REALM': 'my-realm'
})
oidc = OpenIDConnect(app)
@app.route('/protected')
@oidc.require_login
def protected():
user_info = oidc.user_getinfo(['email', 'sub'])
return f'Hello {user_info.get("email")}'
@app.route('/api/data')
@oidc.accept_token(require_token=True)
def api_data():
return {'message': 'Protected API data'}client_secrets.json
{
"web": {
"issuer": "https://keycloak.example.com/realms/my-realm",
"auth_uri": "https://keycloak.example.com/realms/my-realm/protocol/openid-connect/auth",
"client_id": "flask-app",
"client_secret": "client-secret",
"redirect_uris": [
"http://localhost:5000/oidc_callback"
],
"userinfo_uri": "https://keycloak.example.com/realms/my-realm/protocol/openid-connect/userinfo",
"token_uri": "https://keycloak.example.com/realms/my-realm/protocol/openid-connect/token",
"token_introspection_uri": "https://keycloak.example.com/realms/my-realm/protocol/openid-connect/token/introspect"
}
}Docker Compose Example
version: '3'
services:
postgres:
image: postgres:14
environment:
POSTGRES_DB: keycloak
POSTGRES_USER: keycloak
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
keycloak:
image: quay.io/keycloak/keycloak:latest
environment:
KC_DB: postgres
KC_DB_URL: jdbc:postgresql://postgres/keycloak
KC_DB_USERNAME: keycloak
KC_DB_PASSWORD: password
KC_HOSTNAME: localhost
KEYCLOAK_ADMIN: admin
KEYCLOAK_ADMIN_PASSWORD: admin
ports:
- 8080:8080
depends_on:
- postgres
command: start-dev
volumes:
postgres_data:Kubernetes Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: keycloak
spec:
replicas: 2
selector:
matchLabels:
app: keycloak
template:
metadata:
labels:
app: keycloak
spec:
containers:
- name: keycloak
image: quay.io/keycloak/keycloak:latest
args: ["start"]
env:
- name: KC_DB
value: postgres
- name: KC_DB_URL
value: jdbc:postgresql://postgres/keycloak
- name: KC_DB_USERNAME
valueFrom:
secretKeyRef:
name: keycloak-db-secret
key: username
- name: KC_DB_PASSWORD
valueFrom:
secretKeyRef:
name: keycloak-db-secret
key: password
- name: KC_HOSTNAME
value: keycloak.example.com
- name: KEYCLOAK_ADMIN
valueFrom:
secretKeyRef:
name: keycloak-admin-secret
key: username
- name: KEYCLOAK_ADMIN_PASSWORD
valueFrom:
secretKeyRef:
name: keycloak-admin-secret
key: password
ports:
- containerPort: 8080
readinessProbe:
httpGet:
path: /health/ready
port: 8080
livenessProbe:
httpGet:
path: /health/live
port: 8080
---
apiVersion: v1
kind: Service
metadata:
name: keycloak
spec:
selector:
app: keycloak
ports:
- port: 8080
targetPort: 8080
type: LoadBalancerRealm Management
Creating and Configuring Realms
Realm Hierarchy:
- Master realm: Administrative realm (do not use for applications)
- Application realms: Create separate realms per application/environment
Create New Realm:
1. Admin Console → Realm dropdown → Create Realm 2. Set realm name (e.g., production, staging, app-name) 3. Enable/disable realm as needed
Essential Realm Settings
1. General Settings
- Display name: User-friendly name
- HTML display name: Branded name with styling
- Frontend URL: Public-facing URL for realm
- Require SSL: All requests (production) or external requests (dev)
2. Login Settings
- User registration: Enable if public registration allowed
- Edit username: Allow/disallow username changes
- Forgot password: Enable password reset flow
- Remember me: Session persistence option
- Verify email: Require email verification for new users
- Login with email: Allow email as username
3. Email Settings
- From: Display name and email address
- Reply To: Support email address
- Envelope From: Technical sender address
4. Themes
- Login theme: Customize login pages
- Account theme: User account management UI
- Admin console theme: Admin UI appearance
- Email theme: Email template styling
5. Token Settings
- Access token lifespan: 5-15 minutes (default: 5 min)
- SSO session idle: 30 minutes
- SSO session max: 10 hours
- Client session idle: 30 minutes
- Offline session idle: 30 days
6. Session Management
- SSO Session Idle: Inactivity timeout
- SSO Session Max: Absolute session timeout
- Offline Session Idle: Remember-me duration
User & Group Administration
User Management
Create Users:
1. Realm → Users → Add User 2. Set username (required), email, first/last name 3. Enable/disable user account 4. Email verified: Mark as verified or require verification 5. Required actions: Set password, verify email, update profile, etc.
User Attributes:
- Username: Unique identifier (immutable if configured)
- Email: Must be unique if email as username enabled
- First Name / Last Name: Display names
- Custom attributes: Key-value pairs for application metadata
Manage Credentials:
- Password: Temporary (user must change) or permanent
- OTP (One-Time Password): TOTP/HOTP configuration
- WebAuthn: Hardware security keys, biometrics
- Reset password: Admin-initiated or user self-service
User Actions:
- Send verify email
- Send password reset
- Impersonate user (for troubleshooting)
- View sessions and events
- Assign roles and groups
Group Management
Create Groups:
1. Realm → Groups → Create Group 2. Set group name and attributes 3. Create subgroups for hierarchical organization
Group Features:
- Hierarchical structure: Parent/child relationships
- Attribute inheritance: Child groups inherit parent attributes
- Role mapping: Assign realm/client roles to groups
- Default groups: Auto-assign to new users
Best Practices:
- Use groups for organizational structure (departments, teams)
- Use roles for permissions and access control
- Assign roles to groups, not individual users when possible
- Leverage group hierarchy for inherited permissions
Security Hardening & Best Practices
Authentication Security
Password Policies
1. Realm Settings → Authentication → Password Policy 2. Add policies:
- Minimum length: 12 characters
- Uppercase characters: 1
- Lowercase characters: 1
- Digits: 1
- Special characters: 1
- Not username: Prevent username in password
- Password history: 5 (prevent reuse)
- Expire password: 90 days
- Not email: Prevent email in password
Brute Force Detection
1. Realm Settings → Security Defenses → Brute Force Detection 2. Enable brute force detection 3. Permanent lockout: Disable (use temporary) 4. Max login failures: 5 5. Wait increment: 60 seconds 6. Max wait: 900 seconds (15 minutes) 7. Failure reset time: 12 hours
SSL/TLS Configuration
- Require SSL: All requests (production)
- Use valid SSL certificates (Let's Encrypt, commercial CA)
- TLS 1.2 or higher
- Strong cipher suites only
Token Security
Token Settings
- Access token lifespan: Short (5-15 minutes)
- Refresh token: Medium (30 minutes to 1 hour idle)
- Use refresh token rotation
- Revoke refresh tokens on logout
Token Validation
- Verify signature (RSA, HMAC)
- Validate issuer (
issclaim) - Validate audience (
audclaim) - Check expiration (
expclaim) - Validate not before (
nbfclaim)
Admin Security
Admin Account Protection
- Strong passwords (min 16 characters)
- Enable MFA for all admin accounts
- Limit admin accounts to minimum necessary
- Use separate admin realm (master realm)
- Disable admin account when not in use
- Audit admin activities regularly
Admin Console Access
- Restrict IP addresses if possible
- Use VPN for remote admin access
- Enable admin events logging
- Set up alerts for admin actions
Auditing & Monitoring
Enable Event Logging
1. Realm Settings → Events 2. Save events: Enable 3. Event listeners: Add jboss-logging or custom listeners 4. Login events: Enable (retention: 30-90 days) 5. Admin events: Enable (retention: 90-180 days)
Event Types to Monitor
- Failed login attempts
- Password changes
- Role/permission changes
- Client configuration changes
- Token issuance and revocation
- Admin actions
Integration with SIEM
- Export events to centralized logging
- Forward to Splunk, ELK, or other SIEM tools
- Set up alerts for suspicious activities
- Regular log review and analysis
Security Checklist
Production Deployment
- [ ] SSL/TLS enabled with valid certificates
- [ ] Strong password policies enforced
- [ ] Brute force protection enabled
- [ ] MFA enabled for privileged accounts
- [ ] Admin console access restricted
- [ ] Event logging enabled and monitored
- [ ] Regular security audits scheduled
- [ ] Backup and disaster recovery tested
- [ ] Network segmentation implemented
- [ ] Database credentials secured
Regular Maintenance
- [ ] Review and update security policies quarterly
- [ ] Audit user accounts and permissions monthly
- [ ] Monitor and analyze security events weekly
- [ ] Update KeyCloak version within 30 days of release
- [ ] Rotate admin passwords every 90 days
- [ ] Review and remove inactive accounts monthly
- [ ] Test disaster recovery procedures quarterly
- [ ] Security penetration testing annually
Troubleshooting & Diagnostics
Common Issues
1. Users Cannot Login
Symptoms: Login fails, error messages, redirects fail
Diagnosis:
- Check user status: Enabled, email verified
- Check required actions: Password expired, update profile
- Verify client redirect URIs: Must match exactly
- Check authentication flow: Ensure flow is correct
- Review login events: Events → Login Events
Solutions:
- Reset user password (temporary)
- Clear required actions
- Fix redirect URI configuration
- Adjust authentication flow requirements
- Check SSO session status
2. Token Validation Failures
Symptoms: Applications reject tokens, signature validation errors
Diagnosis:
- Verify token signature with realm public key
- Check token expiration time
- Validate issuer URL (must match KeyCloak URL)
- Verify audience claim matches client ID
- Ensure application uses correct realm endpoint
Solutions:
- Use correct realm public key for validation
- Increase token lifespan if too short
- Fix issuer URL in token validation
- Add correct audience to client configuration
- Update application realm endpoint URLs
3. LDAP Sync Issues
Symptoms: Users not syncing, authentication fails for LDAP users
Diagnosis:
- Test LDAP connection: User Federation → Test Connection
- Check bind credentials: Must have read access
- Verify LDAP user DN path
- Check LDAP mappers configuration
- Review KeyCloak server logs
Solutions:
- Fix LDAP connection settings
- Update bind DN credentials
- Correct user DN base path
- Adjust LDAP attribute mappers
- Run manual sync: User Federation → Sync Users
4. Session Expiration Issues
Symptoms: Users logged out unexpectedly, session timeouts
Diagnosis:
- Check SSO session settings: Idle and Max timeouts
- Verify client session settings
- Review remember me configuration
- Check token refresh behavior
- Review events for session termination
Solutions:
- Increase SSO session idle/max timeouts
- Enable remember me for longer sessions
- Implement token refresh in application
- Check for explicit logout calls
- Adjust client session overrides
5. Client Authentication Errors
Symptoms: "Invalid client" or "Unauthorized" errors
Diagnosis:
- Verify client ID and secret
- Check client authentication toggle (ON for confidential)
- Verify redirect URIs match exactly
- Check client enabled status
- Review client credentials in application
Solutions:
- Regenerate client secret if compromised
- Enable client authentication for confidential clients
- Fix redirect URI configuration (remove wildcards)
- Enable client in KeyCloak console
- Update application with correct credentials
Logging & Debugging
Enable Debug Logging
# Edit standalone.xml or standalone-ha.xml
<logger category="org.keycloak">
<level name="DEBUG"/>
</logger>
# Or via CLI
bin/kcadm.sh config credentials --server http://localhost:8080 --realm master --user admin
bin/kcadm.sh update realms/master -s eventsEnabled=true -s adminEventsEnabled=trueLog Locations
- Standalone:
standalone/log/server.log - Docker:
docker logs keycloak - Kubernetes:
kubectl logs <pod-name>
Useful Log Patterns
# Authentication failures
grep "FAILED_LOGIN" server.log
# Token validation issues
grep "Token verification" server.log
# LDAP sync errors
grep "LDAPStorageProvider" server.log
# Database errors
grep "SQLException" server.logDiagnostic Commands
Check Realm Configuration
# Export realm configuration
bin/kcadm.sh get realms/{realm-name}
# Export users
bin/kcadm.sh get users -r {realm-name}
# Export clients
bin/kcadm.sh get clients -r {realm-name}Test Client Configuration
# Get access token (test client credentials)
curl -X POST https://keycloak.example.com/realms/{realm}/protocol/openid-connect/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "client_id={client-id}" \
-d "client_secret={client-secret}" \
-d "grant_type=client_credentials"
# Test password grant
curl -X POST https://keycloak.example.com/realms/{realm}/protocol/openid-connect/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "client_id={client-id}" \
-d "client_secret={client-secret}" \
-d "grant_type=password" \
-d "username={username}" \
-d "password={password}"Token Introspection
# Validate token
curl -X POST https://keycloak.example.com/realms/{realm}/protocol/openid-connect/token/introspect \
-H "Content-Type: application/x-www-form-urlencoded" \
-u "{client-id}:{client-secret}" \
-d "token={access-token}"Performance Issues
Symptoms: Slow login, high response times, timeouts
Diagnosis:
- Check database query performance
- Review connection pool usage
- Monitor JVM memory and GC
- Check cache hit ratios
- Review concurrent session count
Solutions:
- Increase database connection pool
- Optimize database indexes
- Increase JVM heap size (
-Xmx,-Xms) - Tune cache settings
- Scale horizontally (add cluster nodes)
- Enable persistent sessions if using ephemeral storage
Quick Reference Commands
# Start KeyCloak development mode
bin/kc.sh start-dev
# Start KeyCloak production mode
bin/kc.sh start --optimized
# Build for specific database
bin/kc.sh build --db=postgres
# Export realm
bin/kc.sh export --dir /backup --realm my-realm
# Import realm
bin/kc.sh import --dir /backup
# Admin CLI login
bin/kcadm.sh config credentials --server http://localhost:8080 --realm master --user admin
# Create realm via CLI
bin/kcadm.sh create realms -s realm=my-realm -s enabled=true
# Create user via CLI
bin/kcadm.sh create users -r my-realm -s username=john -s enabled=true
# Reset user password via CLI
bin/kcadm.sh set-password -r my-realm --username john --new-password secret
# Get realm info
bin/kcadm.sh get realms/my-realm
# Update realm settings
bin/kcadm.sh update realms/my-realm -s sslRequired=EXTERNALUser Federation
LDAP/Active Directory Integration
Purpose: Sync users from existing directory services
Configure LDAP
1. User Federation → Add Provider → LDAP 2. Edit mode: READ_ONLY, WRITABLE, or UNSYNCED 3. Vendor: Active Directory, Red Hat Directory Server, Other
Connection Settings
- Connection URL:
ldap://ldap.example.com:389orldaps://ldap.example.com:636 - Enable StartTLS: For secure connection on port 389
- Bind DN:
cn=admin,dc=example,dc=com - Bind credential: LDAP admin password
LDAP Search Settings
- Users DN:
ou=users,dc=example,dc=com - Username LDAP attribute:
uidorsAMAccountName(AD) - RDN LDAP attribute:
uidorcn - UUID LDAP attribute:
entryUUIDorobjectGUID(AD) - User object classes:
inetOrgPerson, organizationalPerson
Sync Settings
- Sync registrations: Allow creating LDAP users from KeyCloak
- Import users: Full sync or on-demand (login)
- Periodic full sync: Scheduled synchronization
- Changed users sync: Incremental sync
Active Directory Specific
- Edit mode: WRITABLE (to enable password changes)
- Vendor: Active Directory
- Username attribute:
sAMAccountName - UUID attribute:
objectGUID - User object classes:
person, organizationalPerson, user
LDAP Mappers
- User attribute: Map LDAP attributes to KeyCloak attributes
- Full name: Map
cnto first/last name - Group: Import LDAP groups
- Role: Map LDAP groups to KeyCloak roles
Custom User Federation
Purpose: Integrate with custom user databases or APIs
Implementation
1. Implement UserStorageProvider interface (Java) 2. Package as JAR and deploy to KeyCloak 3. Configure provider in User Federation
Use Cases
- Legacy user databases
- Custom authentication systems
- Third-party user services
- Special validation requirements
User Federation Best Practices
- Use READ_ONLY mode for production LDAP unless password writeback required
- Enable periodic sync for up-to-date user information
- Configure LDAPS or StartTLS for secure connections
- Map only required LDAP attributes
- Test LDAP connection before enabling
- Monitor sync errors in server logs
- Document LDAP/AD schema mappings
- Plan for LDAP downtime scenarios