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";
 
 
  
  env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
  
  //set security credentials
  env.put(Context.SECURITY_AUTHENTICATION,"simple");
  env.put(Context.SECURITY_PRINCIPAL,adminName);
  env.put(Context.SECURITY_CREDENTIALS,adminPassword);
 
  //specify use of ssl
  env.put(Context.SECURITY_PROTOCOL,"ssl");
    
  //connect to my domain controller
  env.put(Context.PROVIDER_URL,ldapURL);
  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"};
   searchCtls.setReturningAttributes(returnedAtts);
  
   //Specify the search scope
   searchCtls.setSearchScope(SearchControls.SUBTREE_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();
 
    totalResults++;
 
    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);
   ctx.close();
 
  } 
  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:
(&(sn=Priya)(mail=*))
 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,



>>>objectClass=person
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!!

Subscribe to GET LATEST ARTICLES!


Related

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

    ReplyDelete
    Replies
    1. Hi,

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

      Hope this helps!

      Delete
  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
    Thanks
    Atul

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

    ReplyDelete
  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..

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

    ReplyDelete
  6. Is is possible to search by Telephone number?

    ReplyDelete
  7. Can we get the current logged in User?

    ReplyDelete
  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?

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

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

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

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

    ReplyDelete
  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

    ReplyDelete

emo-but-icon

SUBSCRIBE


item