Keycloak Active Directory Integration: Complete Enterprise Guide
Last updated: March 2026
Active Directory is the identity backbone of most enterprises. When you deploy Keycloak as your application’s identity provider, integrating with AD lets employees use their existing corporate credentials to log in. No new passwords, no separate accounts, no friction.
Keycloak connects to Active Directory through its LDAP User Federation feature. This creates a live link between AD and Keycloak: when a user logs in, Keycloak queries AD in real-time to validate credentials and retrieve user attributes. Changes in AD (new employees, disabled accounts, group membership changes) are reflected in Keycloak automatically.
This guide covers the complete integration process, from basic LDAP connection setup to advanced features like group synchronization, Kerberos SSO, custom attribute mapping, and troubleshooting.
Prerequisites
Before configuring the integration, ensure:
- Network connectivity. Keycloak must be able to reach your AD domain controller on LDAP (port 389) or LDAPS (port 636). If Keycloak runs in the cloud and AD is on-premises, you need a VPN or private network link.
- Service account. Create a dedicated AD service account for Keycloak with read access to the user and group OUs. This account should have a non-expiring password and be excluded from MFA requirements.
- AD information. You will need the domain controller hostname, base DN, and the DN of your service account.
Gathering AD Information
On a domain-joined Windows machine, run these commands to find the information you need:
# Find domain controllers
nltest /dclist:yourdomain.com
# Find the base DN
dsquery * "" -scope base -attr defaultNamingContext
# Find user OUs
dsquery ou "DC=yourdomain,DC=com"
# Test LDAP connectivity
Test-NetConnection -ComputerName dc01.yourdomain.com -Port 389
Or from a Linux machine with ldapsearch:
# Test LDAP connectivity
ldapsearch -x -H ldap://dc01.yourdomain.com:389
-D "CN=keycloak-svc,OU=Service Accounts,DC=yourdomain,DC=com"
-w "ServiceAccountPassword"
-b "DC=yourdomain,DC=com"
-s base "(objectClass=*)" defaultNamingContext
Configuring LDAP User Federation
Step 1: Add the LDAP Provider
- Log in to the Keycloak admin console
- Select your realm
- Navigate to User Federation
- Click Add LDAP providers
Step 2: Connection Settings
Configure the connection parameters:
| Setting | Value | Notes |
|---|---|---|
| Console Display Name | Active Directory |
Descriptive name for this federation |
| Vendor | Active Directory |
Keycloak adjusts defaults for AD |
| Connection URL | ldaps://dc01.yourdomain.com:636 |
Use LDAPS for encrypted connections |
| Enable StartTLS | Off |
Not needed when using LDAPS |
| Bind Type | simple |
Standard LDAP bind |
| Bind DN | CN=keycloak-svc,OU=Service Accounts,DC=yourdomain,DC=com |
Full DN of your service account |
| Bind Credential | ServiceAccountPassword |
Service account password |
Click Test connection to verify connectivity, then Test authentication to verify the service account credentials.
Step 3: LDAP Search Settings
| Setting | Value | Notes |
|---|---|---|
| Edit Mode | READ_ONLY |
Prevents Keycloak from writing to AD (recommended initially) |
| Users DN | OU=Users,DC=yourdomain,DC=com |
Base OU for user searches |
| Username LDAP attribute | sAMAccountName |
The AD attribute used as username |
| RDN LDAP attribute | cn |
Relative distinguished name attribute |
| UUID LDAP attribute | objectGUID |
Unique identifier in AD |
| User Object Classes | person, organizationalPerson, user |
AD user object classes |
| Search Scope | Subtree |
Search all nested OUs |
Step 4: Synchronization Settings
| Setting | Value | Notes |
|---|---|---|
| Import Users | On |
Import AD users into Keycloak’s local database |
| Sync Registrations | Off |
Do not write new Keycloak users to AD |
| Batch Size | 1000 |
Number of users to process per batch |
| Periodic Full Sync | On |
Enable scheduled full synchronization |
| Full Sync Period | 86400 |
Full sync every 24 hours (in seconds) |
| Periodic Changed Users Sync | On |
Sync changed users more frequently |
| Changed Users Sync Period | 300 |
Changed user sync every 5 minutes |
Using the REST API
You can also configure the federation programmatically. First, get an admin token, then create the LDAP component:
# Acquire admin token
TOKEN=$(curl -s -X POST
"${KEYCLOAK_URL}/realms/master/protocol/openid-connect/token"
-d "client_id=admin-cli"
-d "username=admin"
-d "password=admin"
-d "grant_type=password" | jq -r '.access_token')
# Create LDAP federation
curl -X POST
"${KEYCLOAK_URL}/admin/realms/my-realm/components"
-H "Authorization: Bearer ${TOKEN}"
-H "Content-Type: application/json"
-d '{
"name": "Active Directory",
"providerId": "ldap",
"providerType": "org.keycloak.storage.UserStorageProvider",
"config": {
"vendor": ["ad"],
"connectionUrl": ["ldaps://dc01.yourdomain.com:636"],
"bindDn": ["CN=keycloak-svc,OU=Service Accounts,DC=yourdomain,DC=com"],
"bindCredential": ["ServiceAccountPassword"],
"usersDn": ["OU=Users,DC=yourdomain,DC=com"],
"usernameLDAPAttribute": ["sAMAccountName"],
"rdnLDAPAttribute": ["cn"],
"uuidLDAPAttribute": ["objectGUID"],
"userObjectClasses": ["person, organizationalPerson, user"],
"editMode": ["READ_ONLY"],
"searchScope": ["2"],
"importEnabled": ["true"],
"syncRegistrations": ["false"],
"fullSyncPeriod": ["86400"],
"changedSyncPeriod": ["300"],
"batchSizeForSync": ["1000"]
}
}'
User Attribute Mapping
By default, Keycloak maps basic attributes from AD. You can customize these mappings under the Mappers tab of your LDAP federation.
Default Mappers
Keycloak creates these mappers automatically when you select Active Directory as the vendor:
| Mapper Name | LDAP Attribute | Keycloak Attribute |
|---|---|---|
| username | sAMAccountName |
username |
| first name | givenName |
firstName |
| last name | sn |
lastName |
mail |
email |
Adding Custom Attribute Mappers
Map additional AD attributes to Keycloak user attributes:
- Go to User Federation > Your AD Federation > Mappers
- Click Add mapper
- Select user-attribute-ldap-mapper
Example: mapping the department attribute:
| Setting | Value |
|---|---|
| Name | department |
| Mapper Type | user-attribute-ldap-mapper |
| User Model Attribute | department |
| LDAP Attribute | department |
| Read Only | On |
| Always Read Value From LDAP | On |
| Is Mandatory In LDAP | Off |
To include custom attributes in tokens, create a protocol mapper in your client or client scope. For a detailed guide on mapping attributes to OIDC tokens, see our guide on using custom user attributes in Keycloak OIDC tokens.
Group Synchronization
Syncing AD groups to Keycloak lets you use AD group membership for role-based access control in your applications.
Configure Group Mapper
- In your LDAP federation’s Mappers tab, click Add mapper
- Select group-ldap-mapper
| Setting | Value | Notes |
|---|---|---|
| Name | AD Groups |
Descriptive name |
| LDAP Groups DN | OU=Groups,DC=yourdomain,DC=com |
Where groups are stored in AD |
| Group Name LDAP Attribute | cn |
Group name attribute |
| Group Object Classes | group |
AD group object class |
| Membership LDAP Attribute | member |
Attribute listing group members |
| Membership Attribute Type | DN |
Members referenced by DN |
| Membership User LDAP Attribute | sAMAccountName |
How users are identified in membership |
| Mode | READ_ONLY |
Do not write group changes to AD |
| User Groups Retrieve Strategy | LOAD_GROUPS_BY_MEMBER_ATTRIBUTE |
More efficient for AD |
| Drop Non-Existing Groups During Sync | Off |
Keep groups that no longer exist in AD |
LDAP Filter for Specific Groups
If you only want to sync certain groups, add an LDAP filter:
(&(objectClass=group)(|(cn=App-Users)(cn=App-Admins)(cn=App-Viewers)))
Or filter by OU:
# Set the Groups DN to a specific OU
OU=Application Groups,OU=Groups,DC=yourdomain,DC=com
Mapping AD Groups to Keycloak Roles
After syncing groups, map them to Keycloak realm or client roles:
- Navigate to Groups in your realm
- Find the synced AD group
- Go to Role Mappings
- Assign the appropriate Keycloak roles
This way, an AD user in the App-Admins group automatically gets the app-admin role in Keycloak, which your application can check via the token’s role claims.
Kerberos and SPNEGO SSO
For true single sign-on on corporate networks, configure Kerberos/SPNEGO authentication. Users logged into their Windows workstation are automatically authenticated to Keycloak without entering credentials.
Prerequisites for Kerberos
- Active Directory domain with Kerberos configured (standard in modern AD)
- A Service Principal Name (SPN) registered for Keycloak
- A keytab file for the Keycloak service account
Create the SPN and Keytab
On a domain controller or domain-joined machine:
# Create SPN for Keycloak
setspn -S HTTP/keycloak.yourdomain.com keycloak-svc
# Verify SPN
setspn -L keycloak-svc
# Generate keytab file
ktpass -out keycloak.keytab
-princ HTTP/[email protected]
-mapUser [email protected]
-pass ServiceAccountPassword
-pType KRB5_NT_PRINCIPAL
-crypto AES256-SHA1
Configure Kerberos in Keycloak
In your LDAP federation settings, enable Kerberos:
| Setting | Value |
|---|---|
| Allow Kerberos authentication | On |
| Kerberos Realm | YOURDOMAIN.COM |
| Server Principal | HTTP/[email protected] |
| KeyTab | Path to the keytab file |
| Use Kerberos For Password Authentication | On |
Browser Configuration
Browsers must be configured to send Kerberos tickets to Keycloak’s domain:
Chrome/Edge (via Group Policy or registry):
AuthServerAllowlist: keycloak.yourdomain.com
AuthNegotiateDelegateAllowlist: keycloak.yourdomain.com
Firefox:
Navigate to about:config and set:
network.negotiate-auth.trusted-uris: keycloak.yourdomain.com
When configured correctly, users on domain-joined workstations access your application and are silently authenticated through Kerberos, with Keycloak handling the SPNEGO negotiation transparently. This provides true single sign-on without any user interaction.
LDAP Connection Filtering
Restrict Which Users Can Log In
Use LDAP filters to limit which AD users are visible to Keycloak:
# Only users in a specific group
(&(objectClass=user)(memberOf=CN=Keycloak-Users,OU=Groups,DC=yourdomain,DC=com))
# Only enabled accounts
(&(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))
# Users in specific OUs (combined with Users DN setting)
(&(objectClass=user)(department=Engineering))
Set this filter in the Custom User LDAP Filter field of your federation configuration.
Exclude Service Accounts
Service accounts in AD should typically be excluded from Keycloak:
(&(objectClass=user)(!(sAMAccountName=svc-*)))
Troubleshooting
Connection Failures
If the LDAP connection test fails:
# Test LDAP connectivity from the Keycloak server
# Port 389 (LDAP)
nc -zv dc01.yourdomain.com 389
# Port 636 (LDAPS)
openssl s_client -connect dc01.yourdomain.com:636
# Test LDAP bind
ldapsearch -x -H ldaps://dc01.yourdomain.com:636
-D "CN=keycloak-svc,OU=Service Accounts,DC=yourdomain,DC=com"
-w "password"
-b "DC=yourdomain,DC=com"
"(sAMAccountName=testuser)" cn mail
Common issues:
- Certificate errors with LDAPS: Import the AD CA certificate into Keycloak’s Java truststore
- Connection timeout: Check firewall rules between Keycloak and the domain controller
- Bind failure: Verify the service account DN is correct (use the full distinguished name, not just the username)
SSL Certificate Import for LDAPS
If your AD uses a self-signed or internal CA certificate:
# Export the AD CA certificate
openssl s_client -connect dc01.yourdomain.com:636
-showcerts </dev/null 2>/dev/null |
openssl x509 -outform PEM > ad-ca.pem
# Import into Java truststore (inside Keycloak container)
keytool -importcert -trustcacerts
-file /tmp/ad-ca.pem
-alias "ad-ca"
-keystore /opt/keycloak/conf/truststore.jks
-storepass changeit
-noprompt
# Configure Keycloak to use the truststore
# In keycloak.conf or environment variable:
# KC_SPI_TRUSTSTORE_FILE_FILE=/opt/keycloak/conf/truststore.jks
# KC_SPI_TRUSTSTORE_FILE_PASSWORD=changeit
Users Not Syncing
If users are not appearing in Keycloak after federation setup:
- Trigger a manual sync: Go to User Federation > Your AD > click Sync all users
- Check the LDAP filter: Temporarily remove the custom filter and try again
- Verify the Users DN: Make sure it points to the correct OU
- Check search scope: Set to Subtree to search nested OUs
- Check batch size: If you have more users than the batch size, increase it
- Review Keycloak logs: Enable LDAP debug logging to see the queries being sent
# Enable LDAP debug logging
# Add to keycloak.conf:
# log-level=org.keycloak.storage.ldap:DEBUG
Authentication Failures
If users can see their accounts but cannot log in:
# Test authentication directly against AD
ldapwhoami -x -H ldaps://dc01.yourdomain.com:636
-D "CN=Test User,OU=Users,DC=yourdomain,DC=com"
-w "UserPassword"
Common causes:
- Account locked: Check
lockoutTimeattribute in AD - Password expired: Check
pwdLastSetattribute - Account disabled: Check
userAccountControlflags - Wrong bind format: AD accepts
[email protected]or full DN, but Keycloak sends the configured bind DN format
For other Keycloak errors, see our troubleshooting guides for connection refused, 403 forbidden, and invalid grant errors.
Security Best Practices
- Always use LDAPS (port 636) or StartTLS. Never send credentials over unencrypted LDAP.
- Use a dedicated service account with minimal permissions (read-only access to user/group OUs).
- Set the federation to READ_ONLY unless you specifically need Keycloak to write back to AD.
- Restrict the LDAP filter to only the users and groups your application needs.
- Monitor federation sync through Keycloak’s audit logs and insights.
- Rotate the service account password on a schedule and update Keycloak’s configuration.
Managed Active Directory Integration
If managing the LDAP federation configuration, SSL certificates, and sync schedules feels like overhead, Skycloak provides managed Keycloak hosting where the identity provider configuration is straightforward and supported. Our team can assist with complex AD integration scenarios, and the platform includes built-in session management and security features.
Further Reading
- Keycloak LDAP and Active Directory documentation
- Keycloak LDAP Integration: Step-by-Step Tutorial
- Setting Up SSO with Microsoft in Skycloak
- Using Custom User Attributes in Keycloak OIDC Tokens
- SCIM 2.0 with Skycloak Managed Keycloak
- Keycloak Docker Compose Generator
Need help integrating Keycloak with your enterprise directory? Skycloak provides managed Keycloak hosting with expert support for AD and LDAP federation. See pricing or contact us to discuss your requirements.
Ready to simplify your authentication?
Deploy production-ready Keycloak in minutes. Unlimited users, flat pricing, no SSO tax.