Connecting to LDAP server

In this post under Java LDAP, I will explain how to connect to LDAP server with an example.

Below is the complete code

Main Code

1  import java.util.Hashtable;
2  
3  import javax.naming.Context;
4  import javax.naming.NamingException;
5  import javax.naming.directory.DirContext;
6  import javax.naming.directory.InitialDirContext;
7  
8  public class LDAPDemo1 {
9      public static void main(String[] args) {
10         Hashtable<String, Object> env = new Hashtable<String, Object>();
11         env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
12         env.put(Context.PROVIDER_URL, "ldap://localhost:389");
13         env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=my-domain,dc=com");
14         env.put(Context.SECURITY_CREDENTIALS, "adminpassword");
15         DirContext ctx = null;
16         try {
17             ctx = new InitialDirContext(env);
18         } catch(NamingException excep) {
19             excep.printStackTrace();
20         } finally {
21             if(ctx != null) {
22                 try {
23                     ctx.close();
24                 } catch(NamingException excep) {
25                     excep.printStackTrace();
26                 }
27             }
28         }
29     }
30 }

Since in LDAP, the data is stored in hierarchial manner, at any point in the hierarchy, the parent and its children (direct or indirect) is assumed as context.

To connect to LDAP, we need to create an initial context (i.e., the starting point or root parent in LDAP).

To create a initial context, we need to provide
1) fully qualified name of the service provider as value to Context.INITIAL_CONTEXT_FACTORY key
2) The ipaddress where LDAP server is running as value to PROVIDER_URL key
and/or
3) credentials. If no credentials are provided then it will be anonymous connection to LDAP.

We provide these information in a map and pass the map as an argument to InitialDirContext constructor, as shown at line 17.

These informations are called Environment Properties and passing them in a map data structure is one way of specifying them.

If the instance of “InitialDirContext” is successfully created then we have a successful connection to LDAP server.

At line 23, we close the context by calling the close method.

In this way we can connect to LDAP server.

Leave a comment