Tuesday, March 11, 2008

Using Netscape LDAP APIs with Active Directory

One issue that I encountered with MS Active directory is that typically the DN is set to something like: CN=Srivastava, Ashish, OU=MyDepartment, DC=mydomain, DC=com. The authenticate () method of LDAPConnection needs to have the DN and the user password. Problem is if you need to authenticate a user with his/her NT login name/password, the above DN can not be used. In AD, the login name is stored in sAMAccountName and not in CN. The trick is to use NT login name to search the user in LDAP and then find his DN to authenticate with his password. Following is a sample method to authenticate a user with his NT-login name and password. You would need one user account that has lookup permissions.


public boolean authenticateUser(String uid, String password) {
LDAPConnection ld = null;
boolean isUserValid = false;

try {
// -- Assuming a Pool of LDAPConnections are maintained.
ld = cPool.getConnection();
LDAPSearchResults results;
// -- Search for the user with the samAccountName and then find it's DN to authenticate
results = ld.search(BASE_DN, LDAPConnection.SCOPE_SUB, "(&(samAccountName=" +
uid + "))", new String[] { }, false);
if (results.hasMoreElements()) {
LDAPEntry entry = results.next();
String dn = entry.getDN();
System.out.println ("DN: " + dn);
ld.authenticate(dn, password);
isUserValid = true;
}
} catch (LDAPException e) {
// -- isUserValid = false;
e.printStackTrace();
} finally {
cPool.close(ld);
}
return isUserValid;
}

1 comment:

Moshe said...

Excellent! Thanks!