Listing Active Directory users Spring LDAP

Reading Time: 3 minutes

Hi in this tutorial I will show you how to connect and retrieve user details on windows active directory server. So previously I have posted how to setup an active directory server on windows server 2008 enterprise edition

One by one i will give you the codes and find the full project on github. So let us get started

Person.java

A simple POJO class which holds user attributes

package com.tugrulaslan.domain;

/**
 * Created by Tugrul on 11.02.2014.
 */
public class Person {

    private String name;
    private String displayName;
    private String lastName;
    private String firstName;
    private String mail;
    private String userID;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }

    public String getUserID() {
        return userID;
    }

    public void setUserID(String userID) {
        this.userID = userID;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", displayName='" + displayName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", firstName='" + firstName + '\'' +
                ", mail='" + mail + '\'' +
                ", userID='" + userID + '\'' +
                '}';
    }
}

PersonAttributesMapper.java

We need this attribute mapper class to match the attributes on server with our Contact.java POJO class. we will be implementing Spring LDAP inherit the AttributesMapper interface to our class list of attributes windows servers

package com.tugrulaslan.utils;

import com.tugrulaslan.domain.Person;
import org.springframework.ldap.core.AttributesMapper;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;

/**
 * Created by Tugrul on 11.02.2014.
 */
public class PersonAttributesMapper implements AttributesMapper{

    @Override
    public Object mapFromAttributes(Attributes attributes) throws NamingException {
        Person person = new Person();

        Attribute name = attributes.get("name");
        if (name != null){
            person.setName((String) name.get());
        }

        Attribute displayname = attributes.get("displayname");
        if (displayname != null){
            person.setDisplayName((String) displayname.get());
        }

        Attribute lastname = attributes.get("sn");
        if (lastname != null){
            person.setLastName((String) lastname.get());
        }

        Attribute firstname = attributes.get("givenname");
        if (firstname != null){
            person.setFirstName((String) firstname.get());
        }

        Attribute mail = attributes.get("mail");
        if (mail != null){
            person.setMail((String) mail.get());
        }

        Attribute userid = attributes.get("uid");
        if (userid != null){
            person.setUserID((String) userid.get());
        }

        System.out.println(person.toString());

        return person;
    }
}

PersonDAO.java

Our interface class holds methods will be implemented

package com.tugrulaslan.dao;

import com.tugrulaslan.domain.Person;

import java.util.List;

/**
 * Created by Tugrul on 11.02.2014.
 */
public interface PersonDAO {

    public List<Person> getAllPersons();

    public List findUserByCommonName(String commonName);
}

PersonDAOImpl.java

Our implementation class where we do process incoming request which is implemented to PersonDAO class.

package com.tugrulaslan.dao;

import com.tugrulaslan.domain.Person;
import com.tugrulaslan.utils.PersonAttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tugrul on 11.02.2014.
 */

public class PersonDAOImpl implements PersonDAO{

    private LdapTemplate ldapTemplate;

    public void setLdapTemplate(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }

    protected final static String baseDN = "OU=Domain Controllers";

    @Override
    public List<Person> getAllPersons() {
        List<Person> persons = new ArrayList<Person>();
        try {
            List search = ldapTemplate.search("", "(objectClass=person)", new PersonAttributesMapper());
            persons.addAll(search);
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
        return persons;
    }

    @Override
    public List findUserByCommonName(String commonName) {
            AndFilter andFilter = new AndFilter();
            andFilter.and(new EqualsFilter("objectclass","person"));
            andFilter.and(new EqualsFilter("cn", commonName));
            return ldapTemplate.search("", andFilter.encode(), new PersonAttributesMapper());
    }
}

pom.xml

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.tugrulaslan</groupId>
    <artifactId>SpringLDAP</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringLDAP</name>
    <url>http://maven.apache.org</url>

    <properties>
        <org.springframework.version>3.2.6.RELEASE</org.springframework.version>
        <org.springframework.ldap.version>2.0.0.RELEASE</org.springframework.ldap.version>
        <org.springframework.security.version>3.1.3.RELEASE</org.springframework.security.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-core</artifactId>
            <version>${org.springframework.ldap.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-core-tiger</artifactId>
            <version>${org.springframework.ldap.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-odm</artifactId>
            <version>${org.springframework.ldap.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-ldif-core</artifactId>
            <version>${org.springframework.ldap.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-ldif-batch</artifactId>
            <version>${org.springframework.ldap.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${org.springframework.version}</version>
            <scope>compile</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${org.springframework.security.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${org.springframework.security.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${org.springframework.security.version}</version>
        </dependency>
    </dependencies>
</project>

spring.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util" xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd
                        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        				http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        				http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">


    <bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
        <property name="url" value="ldap://IPORDOMAINADDR:389" />
        <property name="base" value=" DC=DOMAIN,DC=DOMAIN,DC=DOMAIN" />
        <property name="userDn" value="USERNAME" />
        <property name="password" value="PASSWORD" />

    </bean>

    <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
        <constructor-arg ref="contextSource" />
        <property name="ignorePartialResultException" value="true" />
    </bean>

    <bean id="personDAO" class="com.tugrulaslan.dao.PersonDAOImpl">
        <property name="ldapTemplate" ref="ldapTemplate" />
    </bean>

</beans>

App.java

package com.tugrulaslan;

import com.tugrulaslan.dao.PersonDAO;
import com.tugrulaslan.domain.Person;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.List;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        Resource resource = new ClassPathResource("spring.xml");
        BeanFactory beanFactory = new XmlBeanFactory(resource);
        System.out.println(beanFactory.toString());

        PersonDAO personDAO = (PersonDAO) beanFactory.getBean("personDAO");

        List<Person> getAllPersons = personDAO.getAllPersons();
        List findUserByCommonName = personDAO.findUserByCommonName("tugrul");

        System.out.println("All user size: " + getAllPersons.size());
        System.out.println("Found user size: " + findUserByCommonName.size());


    }
}

Final thoughts are that you might be curious how to find out the base value DCs is that log on to your server and type in

dsquery user -name

this command will give you a similar output like this

25