You have users in the LDAP server of your Synology NAS and a Spring Boot application that should let them log in via OIDC. Keycloak sits in the middle. On paper that is three boxes and two arrows. In practice there are a handful of places where it silently goes wrong: an LDAP user that never shows up, a role that never arrives in the token, a login that ends in an endless redirect loop.

This post walks the whole path from the LDAP entry to a working login, and calls out the traps I fell into on the way.

The Big Picture

Synology Directory Server (LDAP)
  │  users, groups
  ▼
Keycloak  (user federation + mappers)
  │  OIDC: ID token with groups and roles
  ▼
Spring Boot application  (oauth2Login)

Three responsibilities, and it helps to keep them apart:

  • LDAP knows who a person is (uid, mail, group membership).
  • Keycloak authenticates and turns LDAP data into a token.
  • The application trusts the token and maps claims to its own authorities.

The application does not need to know that LDAP exists at all.

Step 1: Look at the Directory with a Real LDAP Browser

The Synology user interface shows users and groups as flat lists. It does not show the directory tree. Entries that live in custom organizational units may not appear there at all, which can be very confusing later when Keycloak imports users you cannot find on the NAS.

Use an LDAP browser (there are plugins for IDEs, or standalone tools) and connect to the Synology directory. What you want to find out:

  • Where do the users live? In my case: cn=users,dc=example,dc=com.
  • Where do the groups live? In my case: cn=groups,dc=example,dc=com.
  • How is group membership stored?

Open a user entry. This is what mine looked like (shortened):

entryDN:       uid=jane,cn=users,dc=example,dc=com
uid:           jane
mail:          jane@example.com
objectClass:   posixAccount, inetOrgPerson, ...
memberOf:      cn=users,cn=groups,dc=example,dc=com
               cn=appadmins,cn=groups,dc=example,dc=com

Two things to note down: the DN of the user container and the fact that the user carries a memberOf attribute. The latter makes group handling in Keycloak much easier (see step 5).

Do not assume the layout. I had a design document that described ou=people and ou=groups. The real directory used cn=users and cn=groups. Keycloak happily accepts a wrong DN when you save the configuration and only fails later, at login time.

Step 2: Create a Read-Only Bind User

Keycloak needs an account to search the directory. Create a dedicated user (I called it keycloak-bind) and give it read access only. In the Synology user wizard, add it to the directory group meant for read-only consumers and not to any administrator group.

Treat this account as infrastructure. If somebody deletes it later, every user search in Keycloak breaks. The symptom in the admin console is an unhelpful:

No users found, could be due to wrongly configured federated provider
unknown_error — Cannot parse the JSON

Step 3: Add the LDAP User Federation in Keycloak

In the Keycloak admin console, select your realm, then User federation → Add LDAP provider. The important settings:

SettingValue
VendorOther
Connection URLldap://<nas-ip>:389 (or ldaps:// on 636)
Bind DNDN of your bind user
Bind credentialits password
Users DNcn=users,dc=example,dc=com
Username LDAP attributeuid
RDN LDAP attributeuid
UUID LDAP attributeentryUUID
User object classesinetOrgPerson, posixAccount
Edit modeREAD_ONLY

Use Test connection and Test authentication. Both have to be green before you continue.

READ_ONLY matters: in WRITABLE mode, deleting an imported user in Keycloak can delete it in the directory as well.

Users Are Imported Lazily

Keycloak does not copy the whole directory on save. Users are imported when they log in or when you search for them. An empty user list right after setup is normal. Search for * or use Action → Sync all users on the federation.

Step 4: Watch Out for Duplicate Emails and Local Users

Two traps here, and both cost me an evening.

Duplicate emails. Keycloak does not allow the same email address twice in a realm (unless you enable Duplicate emails in the realm login settings). On my Synology, several accounts (admin, administrator, my own user) carried the same email address. The first one imported won, and my own user could not be imported at all.

Options:

  • Clear or change the email on accounts that do not need to log in.
  • Restrict what gets imported with a Custom User LDAP Filter on the federation, for example only members of one group:
(memberOf=cn=appadmins,cn=groups,dc=example,dc=com)

A local user with the same username. If a user named jane already exists locally in Keycloak, it shadows the LDAP user. The login works, but with the local account’s email and roles, and the LDAP data is ignored. Check Users → jane for the Federation Link badge. If it is missing, you are looking at a local account. Delete or disable it, then log in again so that Keycloak imports the LDAP user.

Step 5: Bring LDAP Groups into Keycloak

Open the federation and go to Mappers → Add mapper → group-ldap-mapper:

SettingValue
LDAP Groups DNcn=groups,dc=example,dc=com
Group Name LDAP Attributecn
Group Object Classeswhatever your group entry uses (posixGroup, groupOfNames, …)
User Groups Retrieve StrategyGET_GROUPS_FROM_USER_MEMBEROF_ATTRIBUTE
Member-Of LDAP AttributememberOf
ModeREAD_ONLY

The memberOf strategy reads the groups from the user entry, so you do not need to know how the group stores its members (member, memberUid, …).

Then run Action → Sync LDAP Groups To Keycloak. The groups show up under Groups, and Users → jane → Groups lists the memberships.

The Wrong Groups DN Breaks the Login, Not Only the Mapper

This was the nastiest part. My mapper pointed to ou=groups,..., which does not exist. Nothing complained when I saved it. But from then on:

  • The user’s Role mapping tab in the admin console showed only unknown_error.
  • The token endpoint of the login returned HTTP 500.

The Keycloak server log finally gave it away:

javax.naming.NameNotFoundException: [LDAP: error code 32 - No Such Object];
remaining name 'ou=groups,dc=example,dc=com'

Whenever Keycloak builds a token it loads the user’s groups, and that query failed. If your login breaks after you touch a mapper, read the server log first.

Step 6: Create the Client and a Role for the Application

Create an OIDC client for the application: Clients → Create client.

  • Client type: OpenID Connect
  • Client ID: for example myapp
  • Client authentication: On (confidential client), and note the secret from the Credentials tab
  • Valid redirect URIs: https://myapp.example.com/login/oauth2/code/keycloak

Then create a client role that your application understands: Clients → myapp → Roles → Create role, for example managers.

Now connect the LDAP group to that role through a Keycloak group:

  1. Groups → appadmins → Role mapping → Assign role
  2. Choose Filter by clients, select myapp managers.

Everyone in the LDAP group appadmins now gets the client role managers, and you maintain the membership only in the directory.

Step 7: Make Sure the Role Ends Up in the ID Token

My application reads the roles from the ID token, so the client roles mapper has to write them there. The dedicated scope of the client (myapp-dedicated) can be empty, that is normal. The mapper lives in the shared client scope roles:

  1. Client scopes → roles → Mappers → client roles
  2. Add to ID token must be On.
  3. The roles scope must be assigned to your client as a default scope (Clients → myapp → Client scopes).

Check the Result Before You Touch the Application

Do not debug this through the application. Use Clients → myapp → Client scopes → Evaluate, select the user and open Generated ID token. The relevant parts of mine:

{
  "iss": "https://keycloak.example.com/realms/myrealm",
  "aud": "myapp",
  "preferred_username": "jane",
  "email": "jane@example.com",
  "groups": ["appadmins", "users"],
  "resource_access": {
    "myapp": { "roles": ["managers"] }
  }
}

If managers is missing here, the problem is in steps 5 to 7. If it is present, the application is next.

Step 8: Configure Spring Boot

The registration needs the issuer, client id and secret:

spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: myapp
            client-secret: ${KEYCLOAK_CLIENT_SECRET}
            scope: openid,profile,email,roles
        provider:
          keycloak:
            issuer-uri: https://keycloak.example.com/realms/myrealm

The roles scope is what pulls in the client roles mapper from step 7. Spring Security then needs to turn resource_access.myapp.roles into authorities:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/css/**", "/js/**", "/actuator/**").permitAll()
            .anyRequest().authenticated())
        .oauth2Login(oauth2 -> oauth2
            .userInfoEndpoint(userInfo -> userInfo
                .userAuthoritiesMapper(keycloakAuthoritiesMapper())));
    return http.build();
}

@Bean
@SuppressWarnings("unchecked")
public GrantedAuthoritiesMapper keycloakAuthoritiesMapper() {
    return authorities -> authorities.stream()
        .filter(OidcUserAuthority.class::isInstance)
        .map(OidcUserAuthority.class::cast)
        .map(a -> a.getIdToken().getClaims())
        .map(claims -> Optional.ofNullable((Map<String, Object>) claims.get("resource_access"))
            .map(ra -> (Map<String, Object>) ra.get("myapp"))
            .map(c -> (List<String>) c.get("roles"))
            .orElse(List.of()))
        .flatMap(Collection::stream)
        .map(role -> (GrantedAuthority) new SimpleGrantedAuthority("ROLE_" + role))
        .collect(Collectors.toSet());
}

With that, hasRole('managers') and @PreAuthorize("hasRole('managers')") work as usual.

Debugging the Login Loop

A very common symptom is an endless redirect between the application and Keycloak. The browser network tab shows this sequence repeating:

auth?response_type=code&client_id=myapp...     (to Keycloak)
login/oauth2/code/keycloak?state=...&code=...  (back to the app)
login?error                                     (the app rejects the login)
oauth2/authorization/keycloak                   (and it starts over)

Keycloak thinks the login is fine, the application disagrees. The reason is invisible at the default log level. Turn on debug logging for Spring Security:

logging.level.org.springframework.security=DEBUG
logging.level.org.springframework.security.oauth2=DEBUG

On Kubernetes, you can do this without touching the image:

kubectl set env deploy/myapp \
  LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_SECURITY=DEBUG \
  LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_SECURITY_OAUTH2=DEBUG

and remove them again with a trailing dash:

kubectl set env deploy/myapp \
  LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_SECURITY- \
  LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_SECURITY_OAUTH2-

In my case the log contained one decisive line:

Authentication failed with provider OidcAuthorizationCodeAuthenticationProvider
since [invalid_token_response] ... 500 Internal Server Error on POST request
for ".../protocol/openid-connect/token"

The application was innocent. Keycloak failed while issuing the token, because of the wrong groups DN from step 5. The matching server log entry led to the fix.

Checklist

When something does not work, go through it from the bottom up:

  1. LDAP browser: do the user and the group exist where you think they do? Is memberOf set?
  2. Federation: do Test connection and Test authentication succeed? Can you find the user under Users?
  3. User details: is there a Federation Link, and does the email look like the LDAP one?
  4. User → Groups: is the LDAP group listed?
  5. Evaluate tab: does the generated ID token contain the group and the client role?
  6. Application log with debug level: what exactly does the OIDC provider complain about?
  7. Keycloak server log: any LDAP: error code?

Every problem I had was visible at one of these seven places. The trick is to stop guessing and look at the first place where the data is wrong.