Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Timeout Value for LDAP authentication at Spring Boot

I use Spring LDAP authentication via:

auth
            .ldapAuthentication()
            .userSearchFilter("userPrincipalName={0}")
            .contextSource()
            .managerDn(ldapAuthenticationConfig.getManagerDn())
            .managerPassword(ldapAuthenticationConfig.getManagerPassword())
            .url(ldapAuthenticationConfig.getUrl());

However, it takes too much time at login page when LDAP server is unavailable. I want to learn whether I can login or not within a considerable time.

Here is the dependency that I use:

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-ldap</artifactId>
    </dependency>

How can I set a timeout value for LDAP authentication at Spring Boot?

like image 340
kamaci Avatar asked Feb 28 '17 19:02

kamaci


1 Answers

I also encountered this problem, and found several answers pointing out the com.sun.jndi.ldap.connect.timeout environment variable, but could not find how to add to Spring Security with Java Config.

To accomplish it, first extract the creation of the context source:

@Autowired
private DefaultSpringSecurityContextSource context;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
    authenticationManagerBuilder
                .ldapAuthentication()
                .userSearchFilter(LDAP_USER_SEARCH_FILTER)
                .contextSource(context);
}

Then, when creating the context source (I did it in the same confiuration class, without builder), you can specify environment properties, and you can add there the timeout attribute:

@Bean
public DefaultSpringSecurityContextSource createContext() {
    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(LDAP_SERVER);
    contextSource.setUserDn(LDAP_MANAGER_DN);
    contextSource.setPassword(LDAP_MANAGER_PASSWORD);

    Map<String, Object> environment = new HashMap<>();
    environment.put("com.sun.jndi.ldap.connect.timeout", LDAP_TIMEOUT);
    contextSource.setBaseEnvironmentProperties(environment);
    return contextSource;
}

Note that uppercase LDAP_ variables are all constants in my config class.

like image 149
Máthé Endre-Botond Avatar answered Oct 08 '22 13:10

Máthé Endre-Botond