Skip to content
Hands-on IT IT Drills

Day 8: Groups and Roles from LDAP

Goal: Bring the groups from the directory into Keycloak, give them the notes roles and see how a group change in LDAP arrives in the token right away. · Duration: approx. 60 min · Prerequisite: Day 7

Briefing

  • The group LDAP mapper maps groups from the directory to Keycloak groups. It reads the membership from member (or from memberOf).
  • The groups get their roles in Keycloak. The directory says who is in which group, Keycloak says what the group may do.
  • Modes: READ_ONLY (memberships from LDAP and Keycloak merged, new ones only in Keycloak), LDAP_ONLY (LDAP only, changes go there), IMPORT (take over once, then Keycloak only).
  • Keycloak keeps imported users including their groups in the cache; changes in LDAP do not always arrive immediately.
 LDAP cn=notes-schreiber (member: carla) ─► Keycloak group notes-schreiber
                                             └─ roles notes-schreiben, notes-lesen
 Login carla ─► Token: groups ["notes-schreiber"], roles [notes-schreiben, …]

Drill 1: The Group Mapper

source ~/kc-lab/setup/env.sh
mkdir -p ~/kc-lab/tag08 && cd ~/kc-lab/tag08
kclogin
LID=$(kcadm get components -r lab -q name=openldap --fields id --format csv --noquotes)
L="-x -H ldap://localhost -D cn=admin,dc=notes,dc=lab -w lab-ldap-pw-123"
kcadm create components -r lab -s name=gruppen -s providerId=group-ldap-mapper \
  -s providerType=org.keycloak.storage.ldap.mappers.LDAPStorageMapper -s parentId=$LID \
  -s 'config."groups.dn"=["ou=groups,dc=notes,dc=lab"]' \
  -s 'config."group.name.ldap.attribute"=["cn"]' \
  -s 'config."group.object.classes"=["groupOfNames"]' \
  -s 'config."membership.ldap.attribute"=["member"]' \
  -s 'config."membership.attribute.type"=["DN"]' \
  -s 'config."membership.user.ldap.attribute"=["uid"]' -s 'config.mode=["READ_ONLY"]' \
  -s 'config."user.roles.retrieve.strategy"=["LOAD_GROUPS_BY_MEMBER_ATTRIBUTE"]' \
  -s 'config."preserve.group.inheritance"=["false"]' -s 'config."groups.path"=["/"]' \
  -s 'config."drop.non.existing.groups.during.sync"=["false"]'
MID=$(kcadm get components -r lab -q name=gruppen --fields id --format csv --noquotes)

Expected (abridged):

Logging into http://localhost:8080 as user kcadmin of realm master
Created new component with id '6a978d9f-…'

Save your progress? Sign up for free

Drill 2: Fetching the Groups

kcadm create user-storage/$LID/mappers/$MID/sync -r lab -q direction=fedToKeycloak -o \
  | jq -c '{added, status}'
kcadm get groups -r lab --fields name --format csv --noquotes | sort
uid() { kcadm get users -r lab -q username=$1 -q exact=true --fields id \
  --format csv --noquotes; }
kcadm get users/$(uid carla)/groups -r lab --fields name --format csv --noquotes

Expected:

{"added":2,"status":"2 imported groups, 0 updated groups, 0 removed groups"}
leser
notes-leser
notes-schreiber
team-notes
notes-schreiber

leser and team-notes come from Day 2, the other two from the directory. carla is a member of notes-schreiber without anyone having added her in Keycloak. In the console under Groups, notes-schreiber, Members:

The members of the LDAP group notes-schreiber in Keycloak

Save your progress? Sign up for free

Drill 3: Roles for the Groups

kcadm add-roles -r lab --gname notes-schreiber --rolename notes-schreiben \
  --rolename notes-lesen
kcadm add-roles -r lab --gname notes-leser --rolename notes-lesen
G() {
  curl -s -d grant_type=password -d client_id=notes-cli \
    -d client_secret=lab-client-secret-123 -d username=$1 -d password=lab-user-pw-123 \
    -d 'scope=openid groups' $KC_URL/realms/lab/protocol/openid-connect/token \
    | jq -r .access_token
}
for u in carla dirk; do
  jwt "$(G $u)" | jq -c '{u: .preferred_username, groups,
    notes: (.realm_access.roles | map(select(startswith("notes"))) | sort)}'
done

Expected:

{"u":"carla","groups":["notes-schreiber"],"notes":["notes-lesen","notes-schreiben"]}
{"u":"dirk","groups":["notes-leser"],"notes":["notes-lesen"]}

The group names come from LDAP, the roles from Keycloak. G fetches tokens with the optional scope groups from Day 5.

Save your progress? Sign up for free

Drill 4: carla Writes

api() { docker run --rm --network lab curlimages/curl:8.17.0 -s "$@"; }
api -w ' %{http_code}\n' -X POST -H "Authorization: Bearer $(G carla)" \
  -H 'Content-Type: application/json' -d '{"text":"aus dem Verzeichnis"}' \
  notes-api:8080/notes

Expected (abridged):

{"id":"5bc617e6-…","text":"aus dem Verzeichnis"}
 201

notes-api knows nothing about LDAP. It sees a token with the role notes-schreiben, and that comes from the group in the directory. In the browser, carla can now write just like anna.

Save your progress? Sign up for free

Drill 5: A Change in the Directory

dirk joins the team of writers. That happens in the directory, not in Keycloak:

ldapmodify $L <<'EOF'
dn: cn=notes-schreiber,ou=groups,dc=notes,dc=lab
changetype: modify
add: member
member: uid=dirk,ou=people,dc=notes,dc=lab
EOF
jwt "$(G dirk)" | jq -c .groups
kcadm create clear-user-cache -r lab && echo "Cache geleert"
jwt "$(G dirk)" | jq -c '{groups, notes: (.realm_access.roles
  | map(select(startswith("notes"))) | sort)}'

Expected:

modifying entry "cn=notes-schreiber,ou=groups,dc=notes,dc=lab"

["notes-leser"]
Cache geleert
{"groups":["notes-leser","notes-schreiber"],"notes":["notes-lesen","notes-schreiben"]}

dirk is in the group in the directory, but the first token knows nothing about it. Keycloak keeps imported users including their groups in the cache, and dirk had been in it since Drill 3. Whether a change in LDAP arrives immediately therefore depends on whether the user currently sits in the cache. clear-user-cache clears it; after that, Keycloak reads the groups again. No sync, no restart. A token already issued stays as it was until its exp.

Save your progress? Sign up for free

Drill 6: READ_ONLY Does Not Mean Write-Protected

What happens if someone in Keycloak adds frida to the group notes-leser?

GRP=$(kcadm get groups -r lab -q search=notes-leser --fields id --format csv \
  --noquotes \
  | head -1)
kcadm update users/$(uid frida)/groups/$GRP -r lab -n && echo hinzugefügt
jwt "$(G frida)" | jq -c '{groups}'
ldapsearch $L -b ou=groups,dc=notes,dc=lab -LLL '(cn=notes-leser)' member

Expected:

hinzugefügt
{"groups":["notes-leser","notes-schreiber"]}
dn: cn=notes-leser,ou=groups,dc=notes,dc=lab
member: uid=dirk,ou=people,dc=notes,dc=lab

No error. In READ_ONLY mode, Keycloak merges the memberships from LDAP and from its own database; new ones end up only in Keycloak. The directory knows nothing about it, and whoever checks the group there does not see frida. Clean it up again:

kcadm delete users/$(uid frida)/groups/$GRP -r lab && echo entfernt
jwt "$(G frida)" | jq -c '{groups}'

Expected:

entfernt
{"groups":["notes-schreiber"]}

If the directory is to be the single source of truth, use LDAP_ONLY: Then such changes go into LDAP, and Keycloak stores none of its own.

Save your progress? Sign up for free

Checkpoint

kcadm get-roles -r lab --gname notes-schreiber --fields name --format csv --noquotes \
  | sort

Expected: the roles of the LDAP group.

notes-lesen
notes-schreiben
jwt "$(G carla)" | jq -c .groups

Expected: carla’s group from the directory.

["notes-schreiber"]
kcadm get components/$MID -r lab | jq -r '.config.mode[0]'

Expected: Groups are read from the directory.

READ_ONLY

Challenge

dirk is not switching after all. Remove him from notes-schreiber in the directory again and show that he may no longer write afterwards.

Hint: ldapmodify with delete: member, remember the cache, then a POST with G dirk.

Solution

ldapmodify $L <<'EOF'
dn: cn=notes-schreiber,ou=groups,dc=notes,dc=lab
changetype: modify
delete: member
member: uid=dirk,ou=people,dc=notes,dc=lab
EOF
kcadm create clear-user-cache -r lab && echo "Cache geleert"
api -w ' %{http_code}\n' -X POST -H "Authorization: Bearer $(G dirk)" \
  -H 'Content-Type: application/json' -d '{"text":"dirk"}' notes-api:8080/notes

Expected:

modifying entry "cn=notes-schreiber,ou=groups,dc=notes,dc=lab"

Cache geleert
{"error":"Rolle notes-schreiben fehlt","user":"dirk"}
 403

Without clearing the cache, Keycloak might have kept issuing dirk tokens with notes-schreiben for a while. For revoking permissions, that is dangerous: Set a cachePolicy on the provider that fits your requirements (Enterprise Note).

Save your progress? Sign up for free

Enterprise Note

  • memberOf instead of member: GET_GROUPS_FROM_USER_MEMBEROF_ATTRIBUTE reads the groups from the user entry. Faster with large groups, but needs a well-maintained memberOf (overlay or AD).
  • Nested groups are taken over by Keycloak with preserve.group.inheritance; in Active Directory they are common (Day 9).
  • Roles instead of groups: The role-ldap-mapper turns LDAP groups directly into roles. Groups with roles in Keycloak are more flexible, because the permissions stay in Keycloak.
  • Cache policy: On the LDAP provider, cachePolicy (DEFAULT, EVICT_DAILY, EVICT_WEEKLY, MAX_LIFESPAN, NO_CACHE) determines how long users stay in the cache. For fast revocation, use MAX_LIFESPAN with a short duration, plus short-lived access tokens.