Search code examples
spring-securityactive-directoryldapspring-ldapspring-security-ldap

How to deep into the LDAP tree to find a user who can authenticate in spring ldap security


I want to use spring security ldap authentication. However I would like to traverse ldap tree recursively. Unfortunately I can find a user only one level or depth.

For example , my user tree likes below:

ouUsers: has users (user1, user2 etc) and subtrees (ouGenel, ouYatay).

And subtrees have subtrees and users.

I would like to traverse the ldap tree recursively to authenticate in spring security project.

My spring authencation code is below, what should I change in my code? :

 @Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .ldapAuthentication()
            .userDnPatterns("CN={0},OU=ouUsers")
            .groupSearchBase("ou=ouUsers")
            .contextSource()
            .url(url+"/"+base)
            .managerDn(dn)
            .managerPassword(password)
            .and()
            .passwordCompare()
            .passwordEncoder(new LdapShaPasswordEncoder())
            .passwordAttribute("sn");
}

Thank you


Solution

  • You need to use userSearchFilter() and userSearchBase() instead of userDnPatterns().

    • userDnPatterns tries to match a DN by substituting the user login name in the supplied pattern, appending the base from the LDAP url.

      This is OK if all your users are stored under a single node in the directory.

    • userSearchFilter() on the other hand can be used to match the login name in a regular request, searching down the tree (default SearchScope =SUBTREE) under a certain base. userSearchBase() can optionally be used to set a branch rdn where user entries are located and from which to perform the search. If not specified, the search includes the entire directory starting from the base dn of the LDAP url.

    Replacing userDnPatterns() with the following should be ok :

    .userSearchBase('ou=ouUsers')
    .userSearchFilter('(cn={0})')
    

    https://docs.spring.io/spring-security/site/docs/3.0.x/reference/ldap.html#d0e5940