Thursday 10 August 2017

LDAP Authentication using Spring

Spring LDAP Example:

In this code example we will learn about how to authenticate LDAP user through Spring. This code gives the details about using Spring LDAP for authenticating LDAP user.


1. First of all add Maven dependency to load Spring supported LDAP dependency.
<dependency>
       <groupId>org.springframework.ldap</groupId>
       <artifactId>spring-ldap-core</artifactId>
       <version>2.1.0.RELEASE</version>
</dependency>

2. Place Key store file in application (e.g. Keystore.jks) if it is required. I have saved this in folder to src/main/resources/keystore

3. Configure LDAP bean in spring context file.

 <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:ldap="http://www.springframework.org/schema/ldap"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/ldap
        http://www.springframework.org/schema/ldap/spring-ldap.xsd  ">
      
<bean id="poolingConnManager" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
       <property name="defaultMaxPerRoute" value="20"/>
       <property name="maxTotal" value="20"/>
</bean>
      
<bean id="ldapUrl" class="java.lang.String">
       <constructor-arg value="${ldapUrl}"/>
</bean>

       <ldap:context-source url="${ldapUrl}"
              username="${ldapUserName}" password="${ldapPassword}" />

       <ldap:ldap-template id="ldapTemplate" />

       <bean id="ldapAuthenticator" class="com.ldap.LdapAuthenticator">
       <constructor-arg ref="ldapTemplate"/>
       </bean>
</beans>


4. Create new LdapAuthenticator Java class. This class contends the code for authenticating uses from LDAP server.

@Service("ldapAuthenticator")
public class LdapAuthenticator {

    private final static String KEY_STORE_FILE = "keystore/KeyStore.jks";
    private final static String KEY_STORE_PASSWORD = "changeit";
   
    private LdapTemplate ldapTemplate;
    private String base = "ou=dummy,ou=user,o=dummy";
   
    public LdapAuthenticator(){
    }

    public LdapAuthenticator(final LdapTemplate ldapTemplate) {
       this.ldapTemplate = ldapTemplate;
    }

    public boolean authenticateUser(String userName, String password) {
       boolean isUserAuthenticated = true;
try {

    String keyStorePath = getKeyStoreFilePath();
    System.setProperty("javax.net.ssl.trustStore", keyStorePath);
    System.setProperty("javax.net.ssl.trustStorePassword", KEY_STORE_PASSWORD);
   
           ldapTemplate.authenticate(query().base(base).where("uid").is(userName), password);
       } catch (final org.springframework.ldap.AuthenticationException e) {
           isUserAuthenticated = false;
           throw e;
       }
       return isUserAuthenticated;
    }

    private String getKeyStoreFilePath() {
       ClassLoader classLoader = getClass().getClassLoader();
       File file = new File(classLoader.getResource(KEY_STORE_FILE).getFile());
       return file.getAbsolutePath();
    }
}



5. Create Java Main class to call created method here and to validate LDAP user by passing username and password.

@Service("ldapUserAuthService")
public class LDAPUserAuthService {

@Autowired
private LdapAuthenticator ldapAuthenticator;

public void validateLDAPUser() { 

   boolean isUserValid = false;
   isUserValid = ldapAuthenticator.authenticateUser(“ldap_test”, “123”);
   System.out.println(“Is user authenticated: “+isUserValid);
}


}