Search code examples
javaspringspring-bootspring-securityspring-data

Configuring LDAP on Spring Boot 3


I was experimenting with spring boot 3 and spring security 6.

I configured my spring security to use LDAP authentication via AD, which works fine, but spring boot still doesn't detect a custom 'AuthenticationManager' and generates its own password.

This is how I set up my LDAP authentication:

@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.ldapAuthentication().userSearchBase(userSearchBase).userSearchFilter(userSearchFilter).contextSource()
            .url(url).managerDn(managerDn).managerPassword(ldapPassword);
}

Even after configuring ldap, this is what I get.

enter image description here


Solution

  • First, you must create a context source, which includes your LDAP url (url), your Manager DN or the Base DN from which your users belong (managerDn), your LDAP password to authenticate yourself / your app to the server, and, last but not least, the connection pooling flag for LDAP (setPooled), which is recommended if you have a large number of users.

    @Bean
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(url);
        contextSource.setUserDn(managerDn);
        contextSource.setPassword(ldapPassword);
        contextSource.setPooled(true);
    
        return contextSource;
    }
    

    Second, you must configure the authentication manager object, which will assist spring boot in recognising that you will be using LDAP for authentication.

    @Bean
    AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {
        LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource);
        factory.setUserSearchBase(userSearchBase);
        factory.setUserSearchFilter(userSearchFilter);
    
        return factory.createAuthenticationManager();
    }
    

    Finally, this is entirely optional. If you need to look up an LDAP user in your app, this interface will come in handy.

    @Bean
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(contextSource());
    }