Dev

Designing Keycloak Identity Brokering and LDAP account linking

Compare Keycloak 26.8.2 LDAP User Federation and Identity Brokering, verify First Broker Login re-authentication, and avoid idp-auto-link ATO risks.

Designing Keycloak Identity Brokering and LDAP account linking

Combining corporate LDAP accounts with external OIDC or social logins under a single user identifier (sub) requires separating User Federation from Identity Brokering and blocking unverified email auto-linking. I verified READ_ONLY LDAP synchronization, Keycloak’s default first broker login email conflict flow, and the account takeover (ATO) risk of idp-auto-link on Keycloak 26.8.2 and LLDAP 0.6.3.

All configurations and outputs in this post come from live calls against quay.io/keycloak/keycloak:26.8.2 and lldap/lldap:stable (0.6.3) in an isolated local Docker Compose stack, with no mocked responses.

Moving account linking from app code to a central IdP

In a single backend application, modeling User and SocialAccount as a 1:N relationship in your own database works well, as I covered in my note on multi-social login account linking. Even there, blocking automatic email merging is necessary to prevent account takeover.

That model breaks down once you run multiple internal services or need to unify corporate directory accounts (LDAP/AD) with external OIDC or social providers. Duplicating social_accounts tables, OAuth2 callbacks, and conflict screens across every service causes security policies to drift and fragments user identities across cross-domain SSO apps.

Delegating this layer to Keycloak lets you bind the corporate directory through User Federation (federationLink) and external providers through Identity Brokering (federatedIdentities). Downstream OIDC clients receive one stable sub claim regardless of how the user signed in. Still, a central IdP isn’t always the right trade-off.

CriterionApp-level 1:N social linkingKeycloak Brokering + User Federation
Best fitSingle B2C app with custom signup and withdrawal flowsTwo or more services unifying LDAP/AD and external IdPs
Mapping storagePer-service DB (social_accounts)Single Keycloak Realm (federationLink + federatedIdentities)
Client workloadCustom OAuth2 callbacks and conflict UI per providerOne standard OIDC integration per client app
Operational costNo extra identity infrastructureRunning, backing up, and upgrading Keycloak and its DB

Skip Keycloak Identity Brokering if you only maintain one B2C application, have no LDAP/AD integration planned, and tie login closely to custom onboarding or soft-delete rules. The operational overhead of running Keycloak and customizing its login theme will outweigh the benefits.

User Federation vs. Identity Brokering

Keycloak’s two external identity mechanisms solve different problems and store state differently on the user record.

AspectUser Federation (LDAP/AD)Identity Brokering (OIDC/SAML)
Target systemCorporate directories (LDAP, Active Directory, Kerberos)External IdPs (Google, GitHub, Microsoft Entra ID)
Authentication pathUser enters password on Keycloak; Keycloak runs LDAP bindBrowser redirects to the external IdP login page
Password visibilityKeycloak receives the password to verify against LDAPKeycloak never sees the external IdP password
User record linkfederationLink (single directory provider ID)federatedIdentities (1:N links to external IdPs)
Sync modelScheduled or full user/group sync when importEnabled=trueOn-demand creation or linking during first broker login

A single Keycloak user record can hold both federationLink and federatedIdentities at the same time. Once an external OIDC account is linked to an LDAP-synced user, both login paths issue the same sub to client applications.

flowchart TD
    APP["Client App (OIDC RP)"]
    KC["Keycloak User (alice / single sub)"]
    LDAP["LLDAP 0.6.3 (federationLink)"]
    EXT["External OIDC IdP (federatedIdentities)"]

    APP -->|"Standard OIDC login"| KC
    KC -->|"Backend LDAP bind"| LDAP
    KC -->|"Browser redirect"| EXT

Verifying LDAP User Federation with LLDAP 0.6.3

To test the directory side locally, I paired Keycloak 26.8.2 with LLDAP (0.6.3). This builds on the container options covered in setting up Keycloak 26 for OIDC and production, binding both services to 127.0.0.1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# docker-compose.yml (local reproduction stack, bound to 127.0.0.1)
networks:
  kc-t23-net:
    name: kc-t23-net

services:
  kc-t23-lldap:
    image: lldap/lldap:stable
    container_name: kc-t23-lldap
    networks:
      - kc-t23-net
    ports:
      - "127.0.0.1:18390:3890"
      - "127.0.0.1:18391:17170"
    environment:
      LLDAP_JWT_SECRET: "<LOCAL_TEST_JWT_SECRET>"
      LLDAP_KEY_SEED: "<LOCAL_TEST_KEY_SEED>"
      LLDAP_LDAP_BASE_DN: "dc=example,dc=test"
      LLDAP_LDAP_USER_DN: "admin"
      LLDAP_LDAP_USER_PASS: "<LLDAP_ADMIN_PASS>"
      LLDAP_LDAP_USER_EMAIL: "admin@example.test"

  kc-t23-keycloak:
    image: quay.io/keycloak/keycloak:26.8.2
    container_name: kc-t23-keycloak
    networks:
      - kc-t23-net
    ports:
      - "127.0.0.1:18380:8080"
      - "127.0.0.1:18384:9000"
    environment:
      KC_BOOTSTRAP_ADMIN_USERNAME: "admin"
      KC_BOOTSTRAP_ADMIN_PASSWORD: "<KC_ADMIN_PASS>"
      KC_HEALTH_ENABLED: "true"
      KC_HOSTNAME: "http://127.0.0.1:18380"
      KC_HOSTNAME_BACKCHANNEL_DYNAMIC: "true"
    command: ["start-dev", "--http-port=8080"]

After creating user alice (alice@example.test) and group developers in LLDAP, I registered the LDAP User Storage Provider in corp-realm via POST /admin/realms/corp-realm/components along with a group-ldap-mapper child component. LLDAP uses uid and entryUUID with person object classes, so I set vendor: other and kept editMode: READ_ONLY so the directory stays the source of truth.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
  "name": "lldap-corp",
  "providerId": "ldap",
  "providerType": "org.keycloak.storage.UserStorageProvider",
  "config": {
    "enabled": ["true"],
    "vendor": ["other"],
    "editMode": ["READ_ONLY"],
    "connectionUrl": ["ldap://kc-t23-lldap:3890"],
    "usersDn": ["ou=people,dc=example,dc=test"],
    "bindDn": ["uid=admin,ou=people,dc=example,dc=test"],
    "bindCredential": ["<LLDAP_ADMIN_PASS>"],
    "authType": ["simple"],
    "usernameLDAPAttribute": ["uid"],
    "rdnLDAPAttribute": ["uid"],
    "uuidLDAPAttribute": ["entryUUID"],
    "userObjectClasses": ["person"],
    "searchScope": ["1"],
    "importEnabled": ["true"],
    "syncRegistrations": ["false"]
  }
}

Triggering Sync All Users, querying the imported user, attempting a write via Admin API, and authenticating with the LLDAP password produced the following results:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[1.7] LDAP Sync All Users:
{"ignored": false, "added": 2, "updated": 0, "removed": 0, "failed": 0, "status": "2 imported users, 0 updated users"}

[1.8] Synced user 'alice' in corp-realm:
{
  "id": "f2540f1e-1a1a-4973-a6d8-08d0178e09f9",
  "username": "alice",
  "email": "alice@example.test",
  "federationLink": "5j7oQatLR46-3SxPL2w5Dw",
  "attributes": {
    "LDAP_ENTRY_DN": ["uid=alice,ou=people,dc=example,dc=test"],
    "LDAP_ID": ["e45b50f8-2e9c-37ea-ae26-f1df914f4919"]
  }
}
[1.8b] Synced groups for 'alice': ["developers"]

[1.9] READ_ONLY write attempt via Keycloak Admin API (PUT /users/{id}):
HTTP 400 -> {"field": "firstName", "errorMessage": "error-user-attribute-read-only", "params": ["firstName"]}

[1.10] alice login with LLDAP password:
HTTP 200 -> ID Token claims: {"iss": "http://127.0.0.1:18380/realms/corp-realm", "sub": "f2540f1e-1a1a-4973-a6d8-08d0178e09f9", "preferred_username": "alice", "email": "alice@example.test"}

alice synced with federationLink, LDAP_ENTRY_DN, LDAP_ID, and the developers group. Calling PUT /users/{id} to edit firstName returned HTTP 400 (error-user-attribute-read-only), confirming the read-only guard. Passing an invalid password returned HTTP 400 (invalid_grant).

First Broker Login execution tree and email conflict flow

Next, I created a separate external-idp Realm acting as an external OIDC IdP, added user alice-social with the same email (alice@example.test), and registered it in corp-realm using the default first broker login flow.

Querying GET /admin/realms/corp-realm/authentication/flows/first%20broker%20login/executions on Keycloak 26.8.2 returns this execution tree:

1
2
3
4
5
6
7
8
9
10
11
- [REQUIRED] Review Profile (idp-review-profile)
- [REQUIRED] User creation or linking (Sub-flow)
  - [ALTERNATIVE] Create User If Unique (idp-create-user-if-unique)
  - [ALTERNATIVE] Handle Existing Account (Sub-flow)
    - [REQUIRED] Confirm link existing account (idp-confirm-link)
    - [REQUIRED] Account verification options (Sub-flow)
      - [ALTERNATIVE] Verify existing account by Email (idp-email-verification)
      - [ALTERNATIVE] Verify Existing Account by Re-authentication (Sub-flow)
        - [REQUIRED] Username Password Form for identity provider reauthentication (idp-username-password-form)
        - [CONDITIONAL] First broker login - Conditional 2FA (Sub-flow)
- [CONDITIONAL] First Broker Login - Conditional Organization (Sub-flow)

When alice-social signs in for the first time through /broker/external-idp/login, Keycloak detects the email collision and blocks silent merging until the user proves ownership of the existing alice account.

sequenceDiagram
    participant B as Browser
    participant KC as Keycloak (corp-realm)
    participant EXT as External OIDC IdP

    B->>KC: 1st broker login
    KC->>EXT: OIDC auth redirect
    EXT-->>B: Redirect with code
    B->>KC: /broker/external-idp/endpoint
    KC-->>B: Account already exists
    B->>KC: linkAccount + LDAP password
    KC-->>B: Link federatedIdentities & callback
    Note over B,KC: 2nd login skips conflict flow

Here is the observed HTTP sequence and the resulting user state:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Step D-1 (Confirm link existing account — idp-confirm-link):
  H1     : Account already exists
  Alert  : User with email alice@example.test already exists. How do you want to continue?
  Form   : buttons=[('submitAction', 'updateProfile'), ('submitAction', 'linkAccount')]
  -> submitAction='linkAccount'

Step D-2 (Re-authentication — idp-username-password-form):
  Alert  : Authenticate to link your account with External OIDC IdP
  Form   : inputs=[('username', 'text', 'alice'), ('password', 'password', '')]
  -> submit existing LDAP password for 'alice'
  302 /realms/corp-realm/login-actions/first-broker-login -> /realms/corp-realm/broker/after-first-broker-login
  302 /realms/corp-realm/broker/after-first-broker-login  -> http://127.0.0.1:18399/callback?state=state-first-broker&code=<MASKED>

[2.6] Linked 'alice' state in corp-realm:
  federationLink (LDAP): "5j7oQatLR46-3SxPL2w5Dw"
  federatedIdentities (OIDC):
  [{"identityProvider": "external-idp", "userId": "da1e4d12-dd7c-4828-86b5-865b8c3c709e", "userName": "alice-social"}]

Two details stood out in the run. First, Review Profile (idp-review-profile) defaults to on_missing_info, so Keycloak skipped the profile review form because external-idp already supplied username, email, firstName, and lastName. Second, because SMTP wasn’t configured in corp-realm, Keycloak skipped idp-email-verification and went directly to idp-username-password-form.

After re-authenticating with the LDAP password, Keycloak attached federatedIdentities (external-idp, alice-social) while keeping federationLink intact. The issued ID Token carried the exact same sub (f2540f1e-1a1a-4973-a6d8-08d0178e09f9) as the original LDAP login. On a second broker login from a fresh session with empty cookies, Keycloak bypassed /login-actions/first-broker-login completely and issued a 302 redirect straight from /broker/external-idp/endpoint to the client callback.

Teams sometimes try to remove the extra re-authentication step by replacing Confirm link existing account and Account verification options with Automatically set existing user (idp-auto-link).

Keycloak 26.8.2 documents this provider directly in /authentication/authenticator-providers:

1
2
idp-auto-link (Automatically set existing user):
"Automatically set existing user to authentication context without any verification"

Binding an existing user on email match alone opens a direct account takeover path.

Linking strategyFirst Broker Login behaviorATO risk and allowed scope
Default flow (idp-confirm-link + re-auth / email check)Shows Account already exists and links only after password (plus 2FA) or email verificationSafe default. Claiming a matching email on an external IdP isn’t enough to hijack the account
Unverified auto-link (idp-auto-link)Immediately binds the matching user and attaches federatedIdentitiesHigh risk. Anyone who registers a victim’s corporate email on a loosely verified external IdP inherits their LDAP account and developers group roles

Only consider idp-auto-link for organization-managed IdPs (such as corporate Google Workspace or Microsoft Entra ID) where your organization controls domain ownership and enforces email_verified=true. Never enable it for public social IdPs.

Before rolling out Identity Brokering alongside LDAP User Federation in production, check four items:

  1. Keep LDAP editMode aligned with your source of truth: Use READ_ONLY when LDAP owns user attributes, and route profile or password changes to your directory portal instead of Keycloak.
  2. Configure SMTP if you rely on email verification: Without SMTP, idp-email-verification is skipped; users who don’t know their LDAP password won’t have a fallback path.
  3. Audit Trust Email and custom broker flows in code: Review exported Realm JSON or IaC definitions to ensure idp-auto-link isn’t attached to public social providers.
  4. Drop dev-only flags before deploying: Replace start-dev and sslRequired: "none" with start behind a TLS reverse proxy before exposing broker endpoints.

References

Keycloak is a single sign on solution for web apps and RESTful web services. The goal of Keycloak is to make security simple so that it is easy for application developers to secure the apps and services they have deployed in their organization. Security features that developers normally have to write for themselves are provided out of the box and are easily tailorable to the individual requirements of your organization. Keycloak provides customizable user interfaces for login, registration, administration, and account management. You can also use Keycloak as an integration platform to hook it into existing LDAP and Active Directory servers. You can also delegate authentication to third party identity providers like Facebook and Google.
Keycloak is a single sign on solution for web apps and RESTful web services. The goal of Keycloak is to make security simple so that it is easy for application developers to secure the apps and services they have deployed in their organization. Security features that developers normally have to write for themselves are provided out of the box and are easily tailorable to the individual requirements of your organization. Keycloak provides customizable user interfaces for login, registration, administration, and account management. You can also use Keycloak as an integration platform to hook it into existing LDAP and Active Directory servers. You can also delegate authentication to third party identity providers like Facebook and Google.
This post is licensed under CC BY 4.0 by the author.