Querying Active Directory from java

This is just a stub I often use when configuring AD authentication for various applications. Invariably, I can use this to quickly determine why a given application configuration may be failing.

import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.*;

class TestAD  {
  static DirContext ldapContext;
  public static void main (String[] args) throws NamingException {
    try {
      Hashtable ldapEnv = new Hashtable(11);
      ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      ldapEnv.put(Context.PROVIDER_URL,  "ldap://youradhost:389");
      ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
      ldapEnv.put(Context.SECURITY_PRINCIPAL, "CN=ldapquerydev,OU=LDAP,OU=Service Accounts,OU=Management,DC=domain,DC=com");
      ldapEnv.put(Context.SECURITY_CREDENTIALS, "queryuserpassword");
      ldapContext = new InitialDirContext(ldapEnv);

      SearchControls searchCtls = new SearchControls();

      String returnedAtts[]={"sn","givenName", "samAccountName"};
      searchCtls.setReturningAttributes(returnedAtts);
      searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
      String searchFilter = "(&(objectClass=user))";
      String searchBase = "dc=domain,dc=com";
      NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchCtls);

      while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult)answer.next();
        System.out.println(">>>" + sr.getName());
        Attributes attrs = sr.getAttributes();
        System.out.println(">>>>>>" + attrs.get("samAccountName"));
      }
      ldapContext.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.