Retrieve all users and their roles from LDAP using Java

Mitul Maheshwari picture Mitul Maheshwari · Feb 6, 2014 · Viewed 16k times · Source

I have a Web application. For LDAP I am using Apache Directive Studio. I want to get all the users and their roles in my application.

I am able to get particular information by using the following code.

    import java.util.Properties;
    import javax.naming.Context;
    import javax.naming.NamingException;
    import javax.naming.directory.Attributes;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;

    public class DirectorySample {
        public DirectorySample() {

        }

        public void doLookup() {
            Properties properties = new Properties();
            properties.put(Context.INITIAL_CONTEXT_FACTORY,
                    "com.sun.jndi.ldap.LdapCtxFactory");
            properties.put(Context.PROVIDER_URL, "ldap://localhost:10389");
            try {
                DirContext context = new InitialDirContext(properties);
                Attributes attrs = context.getAttributes("dc=example,dc=com");
                System.out.println("ALL Data: " + attrs.toString());
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
        public static void main(String[] args) {
            DirectorySample sample = new DirectorySample();
            sample.doLookup();
        }

    }

enter image description here
I want to show all users and roles list, so i need to change query or something else Thanks in Advance.

Answer

Ravi picture Ravi · Mar 6, 2014

You can use org.apache.directory.ldap.client.api.LdapConnection for easy search.

Once you bind the connection, do search on the connection. Loop through the cursor to get the object you want. The first parameter should match your the DN of the users parent. Below example is just to give you an idea.

EntryCursor cursor = connection.search( "ou=users, dc=example, dc=com", "(objectclass=*)", SearchScope.ONELEVEL, "*" );

    while ( cursor.next() )
    {
        Entry entry = cursor.get();
            //play with the entry
    }