Query Active Directory from Java using JNDI

Before actually getting into the real topic of how to query active directory from Java, let me give a very high level overview of what A...

Before actually getting into the real topic of how to query active directory from Java, let me give a very high level overview of what Active Directory is all about. Active Directory is a directory service that is created by Microsoft and this is used for authenticating all users and computers in a Windows domain type network. Every Enterprise Organisation will have this active directory service set up to store authentication information of all the users and machines. Active Directory service uses LDAP (Lightweight Directory Access Protocol) for accessing and maintaining distributed directory information services. In situations where one might want to find the email address, phone number or other details of a person in the organisation with the user name while developing some Intranet applications to facilitate user specific functionality, he/she have to query the active directory from the client application. Java provides an API called JNDI, the Java Naming and Directory Interface to look up into the active directory and search for required values. In this post, I am going to explain with a small example on how to query active directory from a Java Application using JNDI.

To query active directory using LDAP and SSL (Secure Socket Layer), you need the following information on the active directory configuration,

1. Admin name (ex: CN=Administrator,CN=Users,DC=ANTIPODES,DC=COM)
2. Admin password (XXXXXXXXX)
3. LDAP url  (ex:  ldap://mydc.antipodes.com:389)

import java.util.Hashtable;
import javax.naming.ldap.*;
import javax.naming.directory.*;
import javax.naming.*;
public class queryactivedirectory
 public static void main (String[] args)
  Hashtable env = new Hashtable();
  String adminName = "CN=Administrator,CN=Users,DC=ANTIPODES,DC=COM";
  String adminPassword = "XXXXXXX";
  String ldapURL = "ldap://mydc.antipodes.com:636";
  //set security credentials
  //specify use of ssl
  //connect to my domain controller
  try {
   // Create the initial directory context
   DirContext ctx = new InitialLdapContext(env,null);
   //Create the search controls   
   SearchControls searchCtls = new SearchControls();
   //Specify the attributes to return
   String returnedAtts[]={"sn","mail","cn","telephonenumber"};
   //Specify the search scope
   //specify the LDAP search filter
   String searchFilter = "(&(objectClass=user)(mail=*))";
   //Specify the Base for the search
   String searchBase = "DC=ANTIPODES,DC=COM";
   //initialize counter to total the results
   int totalResults = 0;
   // Search for objects using the filter
   NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
   //Loop through the search results
   while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult)answer.next();
    System.out.println(">>>" + sr.getName());
    // Print out some of the attributes, catch the exception if the attributes have no values
    Attributes attrs = sr.getAttributes();
    if (attrs != null) {
     try {
     System.out.println("   surname: " + attrs.get("sn").get());
     System.out.println("   firstname: " + attrs.get("givenName").get());
     System.out.println("   mail: " + attrs.get("mail").get());
     catch (NullPointerException e) {
     System.out.println("Errors listing attributes: " + e);
    System.out.println("Total results: " + totalResults);
  catch (NamingException e) {
   System.err.println("Problem searching directory: " + e);

Code Explanation

There are three important arguments that is passed to the directory context's search method. These three parameters are responsible for what is being searched and how it is searched.

NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

1. Search Base
2. Search Filter
3. Search Controls

Search base is the location in the active directory from which the LDAP search begins.

A search filter is a search query expressed in the form of a logical expression. The following search filter specifies that the qualifying entries must have an "sn" attribute with a value of "Priya" and a "mail" attribute with any value:
 Search Controls class encapsulates the factors that determine the scope of search and what attributes are returned as a result of the search.

The output of the above code will look like,

attribute: sn
value: Priya
attribute: mail
value: Priya.B@programming-free.com
attribute: cn
value: Priya B
attribute: telephonenumber
value: +1 408 555 5252
Please leave your valuable comments and queries about this post in the comment sections. Thanks for reading this!!



JNDI 1327283707591513166

Post a Comment

  1. What if there would be more than one Priya found in Active Directory, Shall it print all the matches with priya, or it would print the first one searched ?

    Please help me out............

    Thanks & Regards
    Rahul Gupta

    1. Hi,

      It will print all the names if more than one match found.

      Hope this helps!

  2. Good and helpful. its working but at my side need to put adminName as CN=Users,DC=ANTIPODES,DC=COM" and ldapURL = "ldap://mydc.antipodes.com:389" and has to comment SECURITY_PROTOCAL.
    Keep posting

  3. Nice example &
    good explanation...!!!

  4. Its not working. I just get the following error "Problem searching directory: javax.naming.CommunicationException: WIN-HLTVPTN9PGQ.anu.com:389 [Root exception is java.net.ConnectException: Connection timed out: connect]". Please help me..

  5. Is there any way to connect to ad and list users using socket programming in java?

  6. Is is possible to search by Telephone number?

  7. Can we get the current logged in User?

  8. Hi,

    The information is useful.

    What if, i want to get the data from database first and then i want to push same data to AD?

    1. You will need access to do updates. it would be and ldapadd command.

  9. Attribute 'givenName' used on :73 must be included in :41 else results in "Errors listing attributes: java.lang.NullPointerException"

  10. Unintentional ASMR Relaxing 코인카지노 온라인카지노 우리카지노 Casino with Unintelligible Croupiers (1,5h Compilation)

  11. Planet Hollywood Resort and 메이저추천 Las Vegas 2021

  12. Nice Post,
    Java follows the ‘write once and run anywhere’ principle and can be used for programming applications using different platforms. It has various features such as data binding, platform-independent characteristics, dynamic coding, and multiple security features, making it a versatile programming language. Java Training In Pune. for more info visit: Java Training In Pune