Setting Timeout Value for LDAP authentication at Spring Boot
Asked Answered
H

2

8

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?

Housewares answered 28/2, 2017 at 19:41 Comment(0)
G
10

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.

Giltzow answered 27/2, 2018 at 10:42 Comment(1)
Great! Thank you very much!Elfland
T
6

for those who use .yml or .properties file


  ldap:
    urls: LDAP://[YOUR FAKE DOMAIN OR IP]
    base: dc=fakedomain,dc=com
    username: [AD_USER_NAME]
    password: [AD_USER_PASSWORD]
    base-environment:
      com.sun.jndi.ldap.connect.timeout: 500

I put com.sun.jndi.ldap.connect.timeout: 500 in spring.ldap.base-enviroment

Note: I use spring

<dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
</dependency>
Tetragonal answered 25/10, 2019 at 9:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.