Java - Connect to an LDAP server in Eclipse

by
Jeremy Canfield |
Updated: March 23 2022
| Java articles
Use this markup in a class to make a connection to an LDAP server.
package com.example;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.ldap.InitialLdapContext;
public class ldapDemo {
public static void main(String[] args) throws Exception {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://example.com:389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "your_username");
env.put(Context.SECURITY_CREDENTIALS, "your_password");
try {
new InitialLdapContext(env, null);
System.out.println("Successfully connected to LDAP");
}
catch (AuthenticationException ex) {
System.out.println("Failed - Unable to connect to LDAP");
ex.printStackTrace();
}
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at