Introduction


There are efforts in the industry to do Microsoft Windows Active Directiory integration. Often the first step is to research how to connect to AD using LDAP in general. Explanations are always cryptic, examples may help cut down on time.

The code example below demonstrates how to connect to a Active Directory domain controller using the LDAP protocol. It retrieves the domain group information for a given username. The program is written in Java.

ad_ldaptest program output example


fm@susie112:~> java ad_ldaptest
Connecting to host 10.253.98.108 at port 389...

LDAP authentication successful!
Found Object: CN=frank4dd,CN=Users,DC=frank4dd,DC=com
Found Attribute: memberOf
memberOf: CN=Domain Admins,CN=Users,DC=frank4dd,DC=com
memberOf: CN=acl_security_audit,OU=Global Groups,OU=User,DC=frank4dd,DC=com
memberOf: CN=adm_LINUX_PRD,OU=Global Groups,OU=User,DC=frank4dd,DC=com

ad_ldaptest.c source code


/* --------------------------------------------------------------------------- *
 * file:        ad_ldaptest.java v1.0                                          *
 * author:      5/23/2011 Frank4DD, see http://fm4dd.com/programming           *
 * purpose:     This test program connects to a Actice Directory LDAP using    *
 *              simple bind and returns the groups for a given domain user.    *
 *                                                                             *
 * compile:     javac ad_ldaptest.java                                         *
 * run:         java  ad_ldaptest                                              *
 * --------------------------------------------------------------------------- */

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

public class ad_ldaptest {
  public static void main(String a[]) {

    // set the LDAP authentication method
    String auth_method  = "simple";
    // set the LDAP client Version
    String ldap_version = "3";
    // This is our LDAP Server's IP
    String ldap_host    = "192.168.98.108";
    // This is our LDAP Server's Port
    String ldap_port    = "389";
    // This is our access ID
    String ldap_dn      = "ldapconnect@frank4dd.com";
   // This is our access PW
    String ldap_pw      = "ldappa55!";
    // This is our base DN
    String base_dn      = "DC=frank4dd,DC=com";

    DirContext ctx      = null;
    Hashtable env       = new Hashtable();

    // Here we store the returned LDAP object data
    String dn           = "";
    // This will hold the returned attribute list
    Attributes attrs;

    env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL,"ldap://" + ldap_host + ":" + ldap_port);
    env.put(Context.SECURITY_AUTHENTICATION, auth_method);
    env.put(Context.SECURITY_PRINCIPAL, ldap_dn);
    env.put(Context.SECURITY_CREDENTIALS, ldap_pw);
    env.put("java.naming.ldap.version", ldap_version);

    try{
      System.out.println("Connecting to host " + ldap_host + " at port " + ldap_port + "...");
      System.out.println();

      ctx = new InitialDirContext(env);
      System.out.println("LDAP authentication successful!");

      // Specify the attribute list to be returned
      String[] attrIDs = { "memberOf" };

      SearchControls ctls = new SearchControls();
      ctls.setReturningAttributes(attrIDs);
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

      // Specify the search filter to match
      String filter = "(&(objectClass=user)(sAMAccountName=frank4dd))";

      // Search the subtree for objects using the given filter
      NamingEnumeration answer = ctx.search(base_dn, filter, ctls);

      // Print the answer
      //Search.printSearchEnumeration(answer);

      while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult)answer.next();
        dn = sr.getName();
        attrs = sr.getAttributes();

        System.out.println("Found Object: " + dn + "," + base_dn);
        if (attrs != null) {
          // we have some attributes for this object
          NamingEnumeration ae = attrs.getAll();
          while (ae.hasMoreElements()) {
            Attribute attr = (Attribute)ae.next();
            String attrId = attr.getID();
            System.out.println("Found Attribute: " + attrId);
            Enumeration vals = attr.getAll();
            while (vals.hasMoreElements()) {
              String attr_val = (String)vals.nextElement();
              System.out.println(attrId + ": " + attr_val);
            }
          }
        }
     }

      // Close the context when we're done
      ctx.close();
    } catch (AuthenticationException authEx) {
      authEx.printStackTrace();
      System.out.println("LDAP authentication failed!");
    } catch (NamingException namEx) {
      System.out.println("LDAP connection failed!");
      namEx.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
   }
  }
}

If anybody needs this example identically written in 'C', there is ad_ldaptest.c available for download, helping to migrate code from Java to 'C'. There is also a more advanced Java test program available in the Apache Howto section.

ad_ldap_listgroup - returns all members for a particular domain group


ad_ldap_listgroup.java connects to a Actice Directory LDAP using simple bind and returns all active Windows accounts that belong to this Windows domain group. Active means that their accounts have not been disabled. The group names DN is given as a single argument. It needs to be enclosed in double quotes if the string contains spaces. All the connection parameters are hard-coded in the program, which is OK for me since they do not change.

fm@susie112:~> java ad_ldap_listgroup "CN=acl_secure_transfer,OU=Global Groups,OU=User,DC=frank4dd,DC=com"
Connecting to host 192.168.100.2 at port 389...

LDAP authentication successful!
[ 0] frank4dd      Frank Me
[ 1] starkbe       Benjamin Stark
 ...
[28] adamssi       Sinclair Adams

LDAP search returned 28/30 users in LDAP group CN=acl_secure_transfer,OU=GlobalGroup,OU=User,DC=frank4dd,DC=com.

A identical 'C' program ad_ldap_listgroup.c has been written as a reference.

Source:

See also: