Keycloak - Identity & Access Management
What is Keycloak?
Keycloak is an open-source Identity and Access Management solution that provides comprehensive authentication and authorization services for modern applications and services. It’s designed to secure applications with minimal code changes and maximum flexibility.
Key Features
🔐 Single Sign-On (SSO)
- Seamless authentication across multiple applications
- Remember me functionality
- Session management
- Single logout across all apps
🌐 Identity Brokering & Social Login
Connect with external identity providers:
- Google, Facebook, GitHub
- SAML 2.0 providers
- OpenID Connect providers
- Custom identity providers
👥 User Federation
Integrate with existing user directories:
- LDAP integration
- Active Directory sync
- Kerberos support
- Custom user storage providers
🎭 Standard Protocols
Industry-standard protocol support:
- OpenID Connect
- OAuth 2.0
- SAML 2.0
🎨 Customizable
- Custom themes for login pages
- Localization support
- Custom authentication flows
- Extension points via SPIs
👤 User Management
- Self-registration
- Password policies
- Account management
- User attributes
- Required actions
🔑 Authorization Services
Fine-grained authorization:
- Role-Based Access Control (RBAC)
- Attribute-Based Access Control (ABAC)
- Policy enforcement
- Permission management
Quick Start
Installation
docker run -d -p 8080:8080 --name keycloak \
-e KEYCLOAK_ADMIN=admin \
-e KEYCLOAK_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:26.5.2 start-devAccess Admin Console
Navigate to: http://localhost:8080
Default credentials: admin / admin
Core Concepts
Realms
Isolated namespaces for users, applications, and roles. Think of realms as tenants.
Clients
Applications that will use Keycloak for authentication (web apps, mobile apps, APIs).
Users
End users who will authenticate through Keycloak.
Roles
Permissions assigned to users. Can be realm-level or client-specific.
Groups
Collections of users that share common roles or attributes.
Identity Providers
External authentication sources (Google, SAML providers, etc.).
Configuration
Create a Realm
- Click realm dropdown (top-left)
- Click Create Realm
- Enter realm name (e.g.,
oversight) - Click Create
Create a Client
- Navigate to Clients → Create client
- Set Client ID (e.g.,
oversight-app) - Configure authentication settings
- Set redirect URIs
- Click Save
Create Users
- Navigate to Users → Add user
- Fill in user details
- Click Create
- Set credentials in Credentials tab
Assign Roles
- Navigate to Realm roles or Client roles
- Create roles as needed
- Go to user’s Role mapping tab
- Assign appropriate roles
Authentication Flows
Authorization Code Flow
Standard OAuth 2.0 flow for web applications.
// Redirect to Keycloak for authentication
window.location.href = `${keycloakUrl}/realms/${realm}/protocol/openid-connect/auth?
client_id=${clientId}&
redirect_uri=${redirectUri}&
response_type=code&
scope=openid`;Implicit Flow (Deprecated)
Not recommended for new applications.
Client Credentials Flow
For service-to-service authentication.
curl -X POST "${keycloakUrl}/realms/${realm}/protocol/openid-connect/token" \
-d "client_id=${clientId}" \
-d "client_secret=${clientSecret}" \
-d "grant_type=client_credentials"Resource Owner Password Credentials
Direct username/password authentication.
Client Integration
JavaScript/React
import Keycloak from 'keycloak-js';
const keycloak = new Keycloak({
url: 'http://localhost:8080',
realm: 'oversight',
clientId: 'oversight-app'
});
// Initialize
keycloak.init({ onLoad: 'login-required' })
.then(authenticated => {
console.log('Authenticated:', authenticated);
});
// Get token
const token = keycloak.token;
// Refresh token
keycloak.updateToken(30);
// Logout
keycloak.logout();Spring Boot
@Configuration
@EnableWebSecurity
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(keycloakAuthenticationProvider());
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(
new SessionRegistryImpl());
}
}Python/FastAPI
from fastapi import FastAPI, Depends
from fastapi_keycloak import FastAPIKeycloak
app = FastAPI()
idp = FastAPIKeycloak(
server_url="http://localhost:8080",
client_id="oversight-app",
client_secret="your-secret",
realm="oversight"
)
@app.get("/protected")
def protected_route(user=Depends(idp.get_current_user())):
return {"user": user}Advanced Features
Multi-Factor Authentication
Enable 2FA for enhanced security:
- Navigate to Authentication → Required actions
- Enable Configure OTP
- Users will be prompted to set up 2FA on next login
Custom Themes
Create branded login pages:
# Theme structure
themes/
my-theme/
login/
theme.properties
login.ftl
styles.css
email/
theme.properties
email-verification.ftlEmail Configuration
Set up email for:
- Email verification
- Password reset
- Admin notifications
# Realm Settings → Email
smtp.host=smtp.gmail.com
smtp.port=587
smtp.from=noreply@oversight.com
smtp.auth=true
smtp.ssl=true
smtp.starttls=true
smtp.user=your-email@gmail.com
smtp.password=your-app-passwordEvents & Audit Logging
Track all authentication events:
- Navigate to Realm settings → Events
- Enable Login events and Admin events
- Configure event listeners
Integration with Oversight Components
With Langfuse
Configure Langfuse to use Keycloak:
AUTH_PROVIDER=keycloak
AUTH_KEYCLOAK_ID=oversight-app
AUTH_KEYCLOAK_SECRET=your-secret
AUTH_KEYCLOAK_ISSUER=http://localhost:8080/realms/oversightWith DataHub
Configure DataHub for OIDC:
auth:
oidc:
enabled: true
clientId: oversight-app
clientSecret: your-secret
discoveryUri: http://localhost:8080/realms/oversight/.well-known/openid-configurationSecurity Best Practices
Production Deployment
- Use HTTPS - Always use SSL/TLS in production
- Strong passwords - Enforce password policies
- Token lifespans - Configure appropriate token expiry
- Brute force detection - Enable account lockout
- Regular updates - Keep Keycloak up to date
- Database backups - Regular backup of Keycloak database
- Security headers - Configure proper CORS and CSP
Password Policies
Configure in Realm Settings → Security Defenses:
- Minimum length
- Special characters required
- Uppercase/lowercase requirements
- Password history
- Expiration time
Brute Force Protection
Enable in Realm Settings → Security Defenses:
- Maximum login failures
- Wait increment
- Quick login check
- Minimum quick login wait
- Maximum wait time
High Availability
Clustered Deployment
Deploy multiple Keycloak instances:
# Node 1
docker run -d \
--name keycloak-1 \
-e KC_CACHE=ispn \
-e KC_CACHE_STACK=kubernetes \
quay.io/keycloak/keycloak:26.5.2 start
# Node 2
docker run -d \
--name keycloak-2 \
-e KC_CACHE=ispn \
-e KC_CACHE_STACK=kubernetes \
quay.io/keycloak/keycloak:26.5.2 startDatabase Configuration
Use external database for production:
docker run -d \
-e KC_DB=postgres \
-e KC_DB_URL=jdbc:postgresql://db-host/keycloak \
-e KC_DB_USERNAME=keycloak \
-e KC_DB_PASSWORD=password \
quay.io/keycloak/keycloak:26.5.2 startMonitoring
Admin Console Metrics
View in admin console:
- Active sessions
- User registrations
- Login failures
- Token usage
Prometheus Metrics
Enable metrics endpoint:
docker run -d \
-e KC_METRICS_ENABLED=true \
quay.io/keycloak/keycloak:26.5.2 startAccess metrics at: /metrics
Troubleshooting
Common Issues
Issue: Redirect URI mismatch
Solution: Ensure redirect URIs in Keycloak match your application exactly
Issue: CORS errors
Solution: Add application origin to “Web Origins” in client settings
Issue: Token expired
Solution: Implement token refresh mechanism
Issue: Cannot login
Solution: Check realm name, client ID, and credentials
Use Cases
Enterprise SSO
Single authentication point for all company applications.
API Security
Secure REST APIs with OAuth 2.0 tokens.
Mobile Apps
Authenticate mobile applications with PKCE flow.
Microservices
Service-to-service authentication with client credentials.
Multi-tenancy
Separate realms for different customers or divisions.