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

To query active directory using LDAP and SSL (Secure Socket Layer), you need the following information on the active directory configuration,
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
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
nice piece of code :)
ReplyDeleteWhat 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 ?
ReplyDeletePlease help me out............
Thanks & Regards
Rahul Gupta
Hi,
DeleteIt will print all the names if more than one match found.
Hope this helps!
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.
ReplyDeleteKeep posting
Thanks
Atul
Nice example &
ReplyDeletegood explanation...!!!
Thank you for the feedback.
DeleteIts 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..
ReplyDeleteCheck your active directory credentials.
DeleteThanks,
Priya
Thank a lot :)
DeleteIs there any way to connect to ad and list users using socket programming in java?
ReplyDeleteIs is possible to search by Telephone number?
ReplyDeleteCan we get the current logged in User?
ReplyDeleteHi,
ReplyDeleteThe information is useful.
What if, i want to get the data from database first and then i want to push same data to AD?
You will need access to do updates. it would be and ldapadd command.
DeleteAttribute 'givenName' used on :73 must be included in :41 else results in "Errors listing attributes: java.lang.NullPointerException"
ReplyDeleteLearning Codes
ReplyDeleteNice Post,
ReplyDeleteJava 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
nice, keep posting. Azure Course In Pune
ReplyDeletenice post, keep posting.Angular Training In Pune
ReplyDelete