Satish Satish - 1 year ago 107
Java Question

How do a LDAP search/authenticate against this LDAP in Java

I am playing with LDAP and Java search.
Here's my LDIF export with a simple organization

version: 1

dn: dc=example,dc=com
objectClass: organization
objectClass: dcObject
objectClass: top
dc: example
o: MyOrganization
description: Test Description

dn: ou=people, dc=example,dc=com
objectClass: organizationalUnit
objectClass: top
ou: people
description: All users in demo company

dn: cn=Johnny Doe,ou=people,dc=example,dc=com
objectClass: organizationalPerson
objectClass: person
objectClass: inetOrgPerson
objectClass: top
cn: Johnny Doe
sn: Johnny
homephone: 123-456-7890
ou: Development
uid: jjohnny
userpassword:: johnny

dn: cn=Samuel Johnson,ou=people,dc=example,dc=com
objectClass: organizationalPerson
objectClass: person
objectClass: inetOrgPerson
objectClass: top
cn: Samuel Johnson
sn: Samuel
homephone: 123-456-7890
ou: Accounts
uid: ssam
userpassword:: sammy

How do I run a Java snippet to get all users from the LDAP server? There's no authentication set-up on my Apache DS Directory Server.

Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:10389/dc=example,dc=com");
env.put(Context.SECURITY_AUTHENTICATION, "none");

try {
// Create initial context
DirContext ctx = new InitialDirContext(env);
Object obj = new Object();
// want to print all users from the LDAP server

Answer Source
    try {
        LdapContext ctx = new InitialLdapContext(env, null);
        NamingEnumeration<?> namingEnum ="ou=people,dc=example,dc=com", "(objectclass=user)", getSimpleSearchControls());
        while (namingEnum.hasMore ()) {
            SearchResult result = (SearchResult) ();    
            Attributes attrs = result.getAttributes ();

    } catch (Exception e) {

private SearchControls getSimpleSearchControls() {
    SearchControls searchControls = new SearchControls();
    //String[] attrIDs = {"objectGUID"};
    return searchControls;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download