Friday, November 19, 2010

Java JNDI Tutoriel : Ldap query

Our topic of discussion today will be JNDI (Java Naming and Directory Interface), which is a standard way to query directories for different kind of available informations.
We will see how you can use Java to interact with OpenLdap or any other directory (like Apache OpenDS etc...).
In order to connect to an ldap directory server we will need to know :
  • The server url (in our case localhost)
  • The authentication used : Simple, Digest etc...
  • the base DN, or the root element.
  • Bind DN, the user we will connect to the directory as.
  • Bind password.

so let's add these fields to our class :

   private String serverUrl = "ldap://localhost:389";  
   private String authentication = "simple";  
   private String baseDN = "dc=myComp,dc=net";  
   private String bindDN = "cn=Admin";  
   private String bindPassword = "password";  

We will need to get a DirContext Object which allows us to contact Ldap for adding or querying users or other form of entries, so lets add that field as well :

 private DirContext ldapContext;  

now, inside the init() method, let's establish a connection to the ldap server, and get our DirContext :

     Hashtable ldapEnv = new Hashtable(11);  
     ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");  
     ldapEnv.put(Context.PROVIDER_URL, serverUrl);  
     ldapEnv.put(Context.SECURITY_AUTHENTICATION, authentication);  
     ldapEnv.put(Context.SECURITY_PRINCIPAL, bindDN + "," + baseDN);  
     ldapEnv.put(Context.SECURITY_CREDENTIALS, bindPassword);  
     ldapContext = new InitialDirContext(ldapEnv);  

Now that we got our DirContext, let's query the directory for entries of class inetOrgPerson, of course you can change the query to get whatever entry you want :

 String query = "(objectclass=inetOrgPerson)";  
     SearchControls ctrl = new SearchControls();  
     //Search the sub tree  
     //Return all attributes  
     //Query the directory  
     NamingEnumeration enumeration =, query, ctrl);  

There we go, we got now an enumeration with all the search results our query returned.

1 comment:

  1. Interesting tutorial. I enjoyed reading the information that you have posted above about JAVA. Al credits goes to you. You are looking to be person with great experience in technologies.
    digital signature FAQ