Friday, January 10, 2014

Java Code to Search Active Directory on LDAPS

Here is the sample java code to search Active Directory for user information.

import java.util.Hashtable;
import javax.naming.ldap.*;
import javax.naming.directory.*;
import javax.naming.*;

 
public class searchActiveDirectory {
 public void getUserDetails() {

  Hashtable env = new Hashtable();
  String adminName = "<<DN of the Admin Account>>";
  String adminPassword = "<<Password of Admin Account>>";
  String ldapURL = "
ldaps://<<ADHost>>:636";
  String keystore = "<>";
  String searchBase = "<<Base DN>>";
  System.setProperty("javax.net.ssl.trustStore", keystore);
  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[] = { "sAMAccountName", "sn", "givenName",
     "mail", "description", "userAccountControl","whenCreated","distinguishedName" };

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

   // specify the LDAP search filter
   //String searchFilter = "(&(objectClass=user)(sAMAccountName="+username+"))";
   String searchFilter = "(&(objectClass=user)(!(objectClass=computer))(whenCreated>=20131227000000.0Z))";


   // 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();
    Attributes attrs = sr.getAttributes();
    if (attrs != null) {
     try {
      System.out.println(attrs.get("sAMAccountName").get()+","+attrs.get("whenCreated").get());
      System.out.println(attrs.get("distinguishedName"));
     } catch (NullPointerException e) {
      System.out.println("Errors listing attributes: " + e);
     }
    }
   }
   ctx.close();

  } catch (NamingException e) {
   System.err.println("Problem searching directory: " + e);
  }
 }


 public static void main(String[] args) throws Exception{
  searchActiveDirectory s = new searchActiveDirectory();
  s.getUserDetails(); 
 }
}

No comments: