Example class to connect to Microsoft LDAP server
package ldap;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class ConnectLDAP {
public static void main(String[] args) {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, properties().getProperty("ldap.factories.initctx"));
env.put(Context.PROVIDER_URL,properties().getProperty("ldap.host"));
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, properties().getProperty("ldap.user"));
env.put(Context.SECURITY_CREDENTIALS, properties().getProperty("ldap.password"));
DirContext ctx = null;
try{
ctx = new InitialDirContext(env);
System.out.println("connected");
System.out.println(ctx.getEnvironment());
} catch (NamingException e) {
e.printStackTrace();
}finally{
if(ctx != null){
try {
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
}
private static Properties props;
static Properties properties() {
if(props == null){
props = new Properties();
try {
props.load(ConnectLDAP.class.getResourceAsStream("ldap.properties"));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return props;
}
}
property file in the sample package locatiion
# LDAP parameters
ldap.host =ldap://ldap.server.com:389
ldap.factories.initctx =com.sun.jndi.ldap.LdapCtxFactory
ldap.user=domain\\userName
ldap.password=password