None

Accessing Active Directory LDAP

January 14, 2010

Active Directory exposes an LDAP interface. This makes it possible to talk to the service using an LDAP client.

Authenticating

Here's an example of talking to Active Directory from python code:

>>> import ldap
>>> con = ldap.initialize('ldap://server:port')
>>> dn = 'domain\username'
>>> password = 'password'
>>> con.simple_bind_s(dn,password)
(97, [])
>>>

Determining Your Active Directory DN

I had difficulty working out what form the user would take in Active Directory. This script will show a dialog box containing you user's LDAP DN on the Active Directory server.

Set objADSysInfo = CreateObject("ADSystemInfo")
wscript.echo objADSysInfo.UserName

Put this code in a text file, called FindMyDN.vbs. From the DOS command line run wscript FindMyDN.vbs.

For me, this returns:

CN=Firstname Surname,OU=City,DC=domain,DC=com

Thanks to http://www.mattberther.com/2006/12/14/determining-your-active-directory-dn/ for the tip.

Checking Names

Once your are bound to the server, this bit of python will allow you to check that a user exists on the server.

>>> dn = 'cn=Firstname Surname,OU=City,DC=domain,DC=com'
>>> con.compare_s(dn, 'CN', 'Firstname')
0 
>>> con.compare_s(dn, 'CN', 'Firstname Surname')
1

It returns 0 if there is no match, or 1 if there is a match.

Java

This code will bind to the server from Java

public static void main(String[] args)
{
  System.out.print("Binding...");
  Hashtable lEnv = new Hashtable();
  lEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  lEnv.put(Context.PROVIDER_URL, "ldap://server:port");
  lEnv.put(Context.SECURITY_AUTHENTICATION,"simple");
  lEnv.put(Context.SECURITY_PRINCIPAL,"CN=Firstname Surname,OU=City,DC=domain,DC=com"); 
  lEnv.put(Context.SECURITY_CREDENTIALS,"password");      
  DirContext lContext = null;
  try
  {
    lContext = new InitialDirContext(lEnv);
  } 
  catch (NamingException lException)
  {
    throw new RuntimeException("Problems creating InitialDirContext", lException);
  }
  System.out.println("...done");
}

This is not much use unless you actually know the full details of the user you want to authenticate. This code is much simpler, and only requires the domain/username along with the password:

System.out.print("Binding...");
Hashtable lEnv = new Hashtable();
lEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
lEnv.put(Context.PROVIDER_URL, "ldap://server:port");
lEnv.put(Context.SECURITY_AUTHENTICATION,"simple");
lEnv.put(Context.SECURITY_PRINCIPAL,"domain\\username"); 
lEnv.put(Context.SECURITY_CREDENTIALS,"password");      
DirContext lContext = null;
try
{
  lContext = new InitialDirContext(lEnv);
}
catch (NamingException lException)
{
  throw new RuntimeException("Problems creating InitialDirContext", lException);
}
System.out.println("...done");

}

Useful Links