This example shows how to search a LDAP user using Java.
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
class LdapUserChecker {
public static void main(String[] args) {
boolean result = false;
String ldapDomain = args[0];
String ldapHost = args[1];
String ldapSearchbase = args[2];
String ldapLookupUserID = args[3];
String ldapLookupUserPwd = args[4];
String userID = args[5];
String url = ldapHost.endsWith("/") ? ldapHost + ldapSearchbase : ldapHost + "/" + ldapSearchbase;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, ldapLookupUserID + "@" + ldapDomain);
env.put(Context.SECURITY_CREDENTIALS, ldapLookupUserPwd);
LdapContext context = null;
NamingEnumeration results = null;
try {
context = new InitialLdapContext(env, null);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
results = context.search("", "(sAMAccountName="+userID+")", controls);
if (results.hasMore()) {
result = true;
}
} catch (NamingException e) {
System.out.println("LDAP authenication failed for lookup user: " + ldapLookupUserID);
System.out.println(e.getMessage());
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
}
}
if (context != null) {
try {
context.close();
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
}
if (result) {
System.out.println("User '" + userID + "' exists!");
} else {
System.out.println("User '" + userID + "' does not exist!");
}
}
}
No comments:
Post a Comment