I had written blog post simple and easy to understand about ‘Querying Active Directory using C#’ then I thought to provide similar approach/article ‘Querying Active Directory using Java’, this article is all about how to achieve in Java.

I will take you through below elements in detail-

  • How to get user details or Object from Active Directory based on Username (sAMAccountName)?
  • How to get user details or Object from Active Directory based on user Email ID?

To know more about filters, attributes/properties you can use for active directory query.

Required Details

  • LDAP address (For e.g.: or IP of the Domain Controller/Global Catalog[GC])
  • Port # where would you to like search user details? Detailed Article ( For e.g.: 3289 or 38)
  • Domain Username
  • Domain Password

Useful References

How to do – Step by Step explaination

For an easy understanding perspective; I will be following line by line approach.  Active Directory Class file and example of how to use that Active Directory class file in java program. Downloads of these files you will find below.

Step 1: Compose LDAP address and supply following parameters username, password, ldap address as domain into Active Directory constructor

ActiveDirectory activeDirectory = new ActiveDirectory(username, password, domain);

Step 2:  invoke ‘searchUser’ method with search term, choice and search base

NamingEnumeration<SearchResult> result = 
		activeDirectory.searchUser(searchTerm, choice, “DC=myjeeva,DC=com”);

Step 3: Now you have your search result in ‘result‘ variable

How it works?

Part 1: ActiveDirectory constructor

  • It creates properties instance with given values (ldap address, username, password)
  • It initializes the Directory Context
  • It assign the Search Scope and return attribute names
public ActiveDirectory(String username, String password, String domainController) {
	properties = new Properties();        
	properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	properties.put(Context.PROVIDER_URL, "LDAP://" + domainController);
	properties.put(Context.SECURITY_PRINCIPAL, username + "@" + domainController);
	properties.put(Context.SECURITY_CREDENTIALS, password);
	// initializing active directory LDAP connection
	try {
	    dirContext = new InitialDirContext(properties);
	} catch (NamingException e) {
	// default domain base for search
	domainBase = getDomainBase(domainController);
	// initializing search controls
	searchCtls = new SearchControls();

Part 2: searchUser Method utilizes the filter method to construct the active directory query

public NamingEnumeration<SearchResult> searchUser(String searchValue, 
				String searchBy, String searchBase) throws NamingException {
	String filter = getFilter(searchValue, searchBy);
	// For eg.: "DC=myjeeva,DC=com";
	String base = (null == searchBase) ? domainBase : getDomainBase(searchBase); 
	return, filter, this.searchCtls);

private String getFilter(String searchValue, String searchBy) {
    String filter = this.baseFilter;        
    if(searchBy.equals("email")) {
        filter += "(mail=" + searchValue + "))";
    } else if(searchBy.equals("username")) {
        filter += "(samaccountname=" + searchValue + "))";
    return filter;

Downloadable Artifacts


That’s it, you have learned querying the active directory in java and you can download artifacts.  Try yourself with class provided above and experiment it.

For any queries please leave a comment!

  • pdtechguru
    • jeevatkm

      @pdtechguru Thanks for visiting. I went through above provided link. In windows server you have shown how to pull out attribute values from Active Directory in server GUI. I hope it helps someone on this track!

  • Djouani Ramissa

    Actually I want to query AD for user certificate and I don’t know how to do that ?

    • Jeevanandam M.

      @Djouani Ramissa – Not to worry, I will add the code snippet for user certificate retrieval and manipulation by tomorrow.


      • Jeevanandam M.

        @Djouani Ramissa – Here you go, follow the article for user object retrieval. Code snippet for User Certificate access-

        Object certObj = attrs.get("userCertificate");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);

        InputStream certificateStream = new ByteArrayInputStream(baos.toByteArray());
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Collection certificateCollection = cf.generateCertificates(certificateStream);

        Iterator i = c.iterator()
        while(i.hasNext()) {
        Certificate cert = (Certificate);

        // use your logic here

        If possible, I will write an article for Certificate Manipulation in AD.


  • Fabrizio Alberti

    Hi. Very useful. I see the sample, where i can find the declared package ???

    • Jeevanandam M.

      Thanks, ActiveDirectory class defined in

      Once you download these java files, (links provided above). Open up, will be able to see.

      • Fabrizio Alberti

        Sorry, but I don’t understand what you mean. I don’t need a jar file?

        • Jeevanandam M.

          Hmm, actually I was trying to say is; it is single Java class utilizing JDK classes for AD interaction. So no jar file :)

          • Fabrizio Alberti

            Thanks for your reply, but so I don’t understand how to compile them from Javac command.

          • Jeevanandam M.

            You can compile individually or together, as follows:


            execute SampleUsageActiveDirectory for sample execution providing domain details OR run from any Java/J2EE IDE for execution.

            Please let know, if you have any doubts.

          • Fabrizio Alberti

            After compiling all and running SampleUsageActiveDirectoy say the class was not found..

          • Jeevanandam M.

            Okay, If you’re using these two classes in java project you will not face any issues, since these classes will reside in appropriate package. Will execute smoothly.

            If you would like to execute it from command line. Go-ahead and comment out below line from two java file.

            Then compile it -

            and then execute it -
            java SampleUsageActiveDirectory

            I hope this helps!

          • Fabrizio Alberti

            YES! Thanks a lot.

  • Annapoorna Shanmugam

    This is the error i get when run the file
    Please help me..

    Querying Active Directory Using Java


    Provide username & password for connecting AD

    Enter Domain:


    Enter username:


    Enter password:


    Search by username or email:


    Enter search term:


    Feb 4, 2014 2:05:05 PM ActiveDirectory

    SEVERE: Invalid name: /

    Exception in thread “main” java.lang.NullPointerException

    at ActiveDirectory.searchUser(

    at SampleUsageActiveDirectory.main(