Dev

Keycloak 26 Identity Brokering과 LDAP 계정 연결 설계

Keycloak 26.8.2와 LLDAP 0.6.3 환경에서 User Federation과 Identity Brokering의 차이, First Broker Login 이메일 충돌 재인증 흐름, idp-auto-link의 계정 탈취 위험을 검증합니다.

Keycloak 26 Identity Brokering과 LDAP 계정 연결 설계

사내 LDAP 디렉터리 계정과 외부 소셜·OIDC 로그인을 하나의 사용자 식별자(sub)로 통합할 때, User Federation과 Identity Brokering의 경계를 구분하지 않으면 계정 중복이나 이메일 기반 계정 탈취(ATO)로 이어집니다. Keycloak 26.8.2와 LLDAP 0.6.3 환경에서 READ_ONLY LDAP 동기화, 기본 first broker login 이메일 충돌 재인증, idp-auto-link의 위험 조건을 직접 확인한 결과를 정리했습니다.

이 글의 설정과 실행 출력은 로컬 Docker Compose 환경의 quay.io/keycloak/keycloak:26.8.2와 lldap/lldap:stable(0.6.3)에서 모의 응답 없이 실제 LDAP·Admin REST API·OIDC 브로커 엔드포인트를 호출해 확인했습니다.

앱 내부 다중 소셜 연동에서 중앙 IdP 브로커링으로

단일 서비스에서 여러 소셜 로그인을 붙일 때는 이전에 정리한 다중 소셜 계정 1:N 연동 모델링처럼 애플리케이션 DB에 User와 SocialAccount를 1:N으로 분리하고 복합 유니크 제약으로 관리하는 편이 단순합니다. 이때도 이메일이 같다는 이유만으로 기존 계정에 소셜 계정을 자동 병합하지 않는 규칙이 핵심이었습니다.

하지만 서비스가 여러 개로 늘어나거나 기존 사내 LDAP 계정에 외부 OIDC·소셜 로그인을 함께 붙여야 하면 상황이 달라집니다. 앱마다 social_accounts 테이블과 OAuth2 콜백, 계정 충돌 화면을 중복 구현하면 보안 정책이 서비스별로 어긋나고, 크로스 도메인 SSO 환경에서 사용자 식별자도 분산됩니다.

Keycloak에 계정 연결을 중앙 위임하면 사내 디렉터리는 User Federation(federationLink)으로, 외부 OIDC·SAML 제공자는 Identity Brokering(federatedIdentities)으로 통합하고, 하위 모든 클라이언트 앱에는 동일한 sub 클레임을 발급할 수 있습니다. 다만 모든 프로젝트에 중앙 IdP가 정답은 아닙니다.

비교 항목앱 내부 1:N 소셜 연동Keycloak Brokering + User Federation
적합한 환경단일 B2C 앱, 자체 회원 가입·탈퇴 UX가 복잡한 경우2개 이상 사내·B2B 서비스, LDAP/AD와 외부 IdP 통합
계정 매핑 위치각 서비스 DB (social_accounts)Keycloak 단일 Realm (federationLink + federatedIdentities)
클라이언트 구현 부담제공자별 OAuth2·프로필 파싱·충돌 처리 직접 구현표준 OIDC 클라이언트 연동 1회로 통일
운영 비용별도 인증 인프라 없음Keycloak 컨테이너·DB·백업·업그레이드 운영 필요

서비스가 하나뿐이고 사내 디렉터리 연동 계획이 없으며, 약관 동의나 휴면·탈퇴 흐름이 앱 도메인 로직과 강하게 결합되어 있다면 Keycloak Identity Brokering을 도입하지 않는 편이 낫습니다. 중앙 IdP 운영 비용과 로그인 화면 커스터마이징 부담이 얻는 이점보다 큽니다.

User Federation과 Identity Brokering의 구조적 차이

Keycloak 문서를 처음 볼 때 가장 자주 혼동하는 두 기능이 User Federation과 Identity Brokering입니다. 둘 다 외부 계정을 Keycloak에 연결하지만, 인증 주체와 데이터 저장 방식이 다릅니다.

구분User Federation (LDAP/AD)Identity Brokering (OIDC/SAML)
연결 대상사내 LDAP, Active Directory, Kerberos 등 디렉터리 서버Google, GitHub, Microsoft Entra ID 등 외부 IdP
인증 수행 방식Keycloak 로그인 폼에 비밀번호 입력 후 백엔드 LDAP Bind 검증브라우저를 외부 IdP로 리다이렉트해 외부 화면에서 인증
비밀번호 노출Keycloak이 입력을 받아 LDAP 서버로 검증 요청Keycloak은 외부 IdP 비밀번호를 알지 못함
사용자 레코드 연결federationLink (단일 디렉터리 공급자 ID)federatedIdentities (다수 외부 IdP 1:N 연결)
동기화 특성importEnabled 시 주기·전체 동기화 및 그룹 매핑 지원최초 브로커 로그인 시점에 계정 생성 또는 기존 계정 연결

핵심은 한 명의 Keycloak 사용자 레코드가 federationLink와 federatedIdentities를 동시에 가질 수 있다는 점입니다. 사내 LDAP에서 동기화된 alice 계정에 외부 OIDC IdP 계정을 연결해 두면, 사용자가 LDAP 비밀번호로 로그인하든 외부 IdP로 로그인하든 클라이언트 앱은 같은 sub를 받습니다.

flowchart TD
    APP["클라이언트 앱 (OIDC RP)"]
    KC["Keycloak 사용자 (alice / 단일 sub)"]
    LDAP["LLDAP 0.6.3 (federationLink)"]
    EXT["외부 OIDC IdP (federatedIdentities)"]

    APP -->|"표준 OIDC 로그인"| KC
    KC -->|"백엔드 LDAP Bind"| LDAP
    KC -->|"브라우저 리다이렉트"| EXT

LLDAP 0.6.3과 Keycloak 26.8.2 LDAP User Federation 실측

먼저 LLDAP 경량 디렉터리 서버를 사내 LDAP 역할로 띄우고 Keycloak 26.8.2와 연결했습니다. Keycloak 기본 기동과 호스트네임 옵션은 Keycloak 26 Docker 실행과 운영 설정에서 다룬 구성을 따르며, 로컬 재현용 docker-compose.yml은 다음과 같습니다.

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 (로컬 재현 전용, 포트 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"]

LLDAP에 alice(alice@example.test)와 developers 그룹을 만든 뒤, Keycloak corp-realm에 Admin REST API(POST /admin/realms/corp-realm/components)로 LDAP User Federation을 등록했습니다. LLDAP는 OpenLDAP·AD와 스키마가 조금 다르므로 vendor: other, usernameLDAPAttribute: uid, uuidLDAPAttribute: entryUUID, userObjectClasses: person을 명시하고, 디렉터리를 단일 진실 공급원(SoT)으로 두기 위해 editMode: READ_ONLY를 선택했습니다. 그룹 동기화에는 하위 컴포넌트로 group-ldap-mapper를 추가했습니다.

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"]
  }
}

전체 동기화(Sync All Users)를 실행한 뒤 사용자 조회, READ_ONLY 쓰기 시도, LLDAP 비밀번호 로그인을 차례로 검증한 결과입니다.

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가 federationLink, LDAP_ENTRY_DN, LDAP_ID, developers 그룹과 함께 동기화되었고, READ_ONLY 상태에서 Keycloak Admin API로 firstName을 수정하려 하면 HTTP 400(error-user-attribute-read-only)으로 차단됩니다. 잘못된 비밀번호 입력 시에는 HTTP 400(invalid_grant)이 반환됩니다.

First Broker Login 실행 트리와 이메일 충돌 재인증 흐름

이제 외부 OIDC IdP 역할의 별도 Realm(external-idp)을 만들고, 기존 LDAP alice와 동일한 이메일(alice@example.test)을 가진 alice-social 사용자를 생성해 corp-realm의 OIDC Identity Provider로 등록했습니다.

외부 IdP로 최초 로그인할 때 Keycloak이 실행하는 인증 흐름은 GET /admin/realms/corp-realm/authentication/flows/first%20broker%20login/executions로 확인할 수 있습니다. Keycloak 26.8.2의 기본 트리는 다음과 같습니다.

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)

실제 브라우저 리다이렉트 시퀀스로 corp-realm의 /broker/external-idp/login에 alice-social로 1차 로그인을 수행하면, Keycloak은 자동 병합을 거부하고 소유권 확인 단계로 진입합니다.

sequenceDiagram
    participant B as 브라우저
    participant KC as Keycloak (corp-realm)
    participant EXT as 외부 OIDC IdP

    B->>KC: 1차 브로커 로그인 요청
    KC->>EXT: OIDC 인증 리다이렉트
    EXT-->>B: 코드 발급 후 콜백 이동
    B->>KC: /broker/external-idp/endpoint
    KC-->>B: Account already exists (충돌)
    B->>KC: linkAccount + LDAP 비밀번호
    KC-->>B: federatedIdentities 연결 및 콜백
    Note over B,KC: 2차 로그인은 충돌 없이 즉시 통과

관찰된 HTTP 흐름과 연결 직후 사용자 상태는 다음과 같습니다.

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', '')]
  -> 기존 LDAP 계정 '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] 연결 완료 후 corp-realm 사용자 'alice' 상태:
  federationLink (LDAP): "5j7oQatLR46-3SxPL2w5Dw"
  federatedIdentities (OIDC):
  [{"identityProvider": "external-idp", "userId": "da1e4d12-dd7c-4828-86b5-865b8c3c709e", "userName": "alice-social"}]

이 과정에서 두 가지 세부 조건을 확인했습니다. 첫째, Review Profile(idp-review-profile)의 기본값이 on_missing_info이기 때문에 외부 IdP가 username, email, firstName, lastName을 모두 내려주면 프로필 확인 화면을 생략하고 바로 Account already exists로 넘어갑니다. 둘째, 테스트 Realm에 SMTP 서버를 설정하지 않았으므로 idp-email-verification 분기가 건너뛰어지고 자동으로 idp-username-password-form 재인증 화면이 표시되었습니다.

LDAP 비밀번호로 재인증을 통과하면 alice의 federationLink가 유지된 채 federatedIdentities에 external-idp가 추가되며, 발급된 ID Token의 sub도 기존 LDAP alice의 UUID(f2540f1e-1a1a-4973-a6d8-08d0178e09f9)와 정확히 일치합니다. 이후 쿠키를 비운 새 세션에서 external-idp로 2차 로그인을 시도하면 /login-actions/first-broker-login을 전혀 거치지 않고 /broker/external-idp/endpoint에서 곧바로 클라이언트 콜백으로 302 리다이렉트됩니다.

idp-auto-link의 계정 탈취 위험과 운영 체크리스트

실무에서 사용자가 최초 로그인 때 비밀번호를 한 번 더 입력하는 과정을 줄이려고, first broker login 플로우에서 Confirm link existing account와 Account verification options를 지우고 Automatically set existing user(idp-auto-link)로 바꾸는 경우가 종종 있습니다.

Keycloak 26.8.2 Admin API(/authentication/authenticator-providers)에서 조회한 idp-auto-link의 공식 설명은 다음과 같습니다.

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

검증 없이 이메일 일치만으로 기존 사용자 컨텍스트를 바인딩하면 심각한 계정 탈취 경로가 열립니다.

설계 방식First Broker Login 동작계정 탈취(ATO) 위험과 적용 조건
기본 플로우 (idp-confirm-link + 재인증/이메일 검증)충돌 시 Account already exists 표시 후 기존 비밀번호(및 2FA) 또는 이메일 링크 검증 완료 시에만 연결안전 (권장 기본값). 외부 IdP에서 이메일을 선점해도 기존 계정 소유권 없이는 탈취 불가
검증 없는 자동 병합 (idp-auto-link)이메일·username 일치만으로 기존 사용자에 federatedIdentities 즉시 연결고위험. 외부 IdP에 임의 가입이 가능하거나 이메일 검증이 느슨하면 사내 LDAP 계정과 developers 같은 그룹 권한이 그대로 탈취됨

idp-auto-link는 조직이 도메인 소유권과 계정 발급을 직접 통제하고 email_verified=true를 보장하는 신뢰된 사내 IdP(예: 기업 Google Workspace, Microsoft Entra ID)에 한해서만 제한적으로 검토해야 합니다. 누구나 가입할 수 있는 일반 소셜 IdP에는 적용해서는 안 됩니다.

운영 환경에 Keycloak Identity Brokering과 LDAP User Federation을 함께 배포하기 전에는 아래 항목을 점검하는 편이 안전합니다.

  1. LDAP editMode와 비밀번호 정책 분리: 디렉터리가 마스터라면 READ_ONLY로 고정하고, 비밀번호 변경·프로필 수정 링크는 Keycloak이 아닌 디렉터리 포털로 안내합니다.
  2. SMTP 설정과 idp-email-verification 활성화 여부 확인: 기존 LDAP 사용자가 비밀번호를 잊었거나 패스워드리스 환경이라면 SMTP를 구성해 이메일 검증 분기가 동작하도록 준비합니다.
  3. 외부 IdP의 Trust Email과 이메일 검증 정책 점검: 신뢰할 수 없는 소셜 IdP에 Trust Email과 idp-auto-link를 함께 켜지 않도록 Realm 설정을 코드(IaC)나 Export JSON으로 리뷰합니다.
  4. 로컬 테스트 옵션 분리: 로컬 HTTP 실험에 사용한 start-dev와 sslRequired: "none"은 운영 환경에서 반드시 제거하고 TLS 리버스 프록시와 start 모드로 전환합니다.

참고 자료

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.
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.