2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How to connect with active directory using Java

How to connect with active directory using Java
userimage
To connect with Active Directory Please refer The Below Code:

import javax.naming.*;
import javax.naming.directory.*;

public class ActiveDirectoryConnection
{
  public static DirContext ldapContext;
  public static void main (String[] args) throws NamingException
  {
    try
    {
      Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
      ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      ldapEnv.put(Context.PROVIDER_URL,  "ldap://<host>:<port number>");
      ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
      ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=?,ou=?,dc=?,dc=?");
      ldapEnv.put(Context.SECURITY_CREDENTIALS, "password");
      ldapContext = new InitialDirContext(ldapEnv);

      // Create the search controls        
      SearchControls searchCtls = new SearchControls();

      //Specify the attributes to return
      String returnedAtts[]={"sn","name", "samAccountName"};
      searchCtls.setReturningAttributes(returnedAtts);

      //Specify the search scope
      searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

      //specify the LDAP search filter
      String searchFilter = "(&(objectClass=user))";

      //Specify the Base for the search
      String searchBase = "dc=?,dc=?";
      //initialize counter to total the results
      int totalResults = 0;

      // Search for objects using the filter
      NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);

      //Loop through the search results
      while (answer.hasMoreElements())
      {
        SearchResult sr = (SearchResult)answer.next();

        totalResults++;

        System.out.println(">>>" + sr.getName());
        Attributes attrs = sr.getAttributes();
        System.out.println(">>>>>>" + attrs.get("samAccountName"));
      }

      System.out.println("Total results: " + totalResults);
      ldapContext.close();
    }
    catch (Exception e)
    {
      System.err.println(" Search error: " + e);
      e.printStackTrace();
    }
  }
}
Answer is