Connecting to LDAP/Active Directory using JNDI (Java)
By: Troy Campano
(2008-09-07)
Filed under Articles > Programming > Java

Introduction
LDAP (Lightweight Directory Access Protocol) has become a standard in most companies for storing hierarchical data. Some of the more common uses are storing employee and customer data. It is very similar to a database (in fact most LDAP implementations tend to have an underlying database in which the data is stored) with the main difference being that the data is in a hierarchy (think folders within folders). Java provides an API for communicating with directories like LDAP called JNDI (Java Naming and Directory Interface). Here is a basic example on how to search for a few common attributes using JNDI:


import java.util.Hashtable;



import javax.naming.Context;

import javax.naming.NamingEnumeration;

import javax.naming.NamingException;

import javax.naming.directory.Attributes;

import javax.naming.directory.DirContext;

import javax.naming.directory.SearchControls;

import javax.naming.directory.SearchResult;

import javax.naming.ldap.InitialLdapContext;



public class DirectorySearch {



	public static void main(String[] args) {



		// Define object to hold environmental properties

		Hashtable<String, String> env = new Hashtable<String, String>();



		// My username, password, and URL for LDAP

		String username = "uid=myusername,ou=Users,o=MyCompany";

		String password = "myPassword";

		String url = "ldap://localhost:389";



		// Define connection properties.

		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

		env.put(Context.SECURITY_AUTHENTICATION, "simple");

		env.put(Context.SECURITY_PRINCIPAL, username);

		env.put(Context.SECURITY_CREDENTIALS, password);

		env.put(Context.PROVIDER_URL, url);



		try {



			// Establish the directory context

			DirContext ctx = new InitialLdapContext(env, null);



			// Create a SearchControls object to do some filtering.

			// Define what attributes I want to get back from LDAP

			SearchControls searchCtls = new SearchControls();

			String returnedAtts[] = { "sn", "givenName", "mail" };

			searchCtls.setReturningAttributes(returnedAtts);



			// Specify the scope of my search (one level down,

			// recursive subtree, etc.)

			searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);



			// My ldap search filter...what am I looking for?

			String searchFilter = "(uid=someUserID)";



			// Where to start my search

			String searchBase = "ou=Users,o=MyCompany";



			// Actually perform the search telling JNDI where to start

			// the search, what to search for, what how to filter.

			NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchCtls);



			// Loop through the search results

			while (results.hasMoreElements()) {



				SearchResult searchResult = (SearchResult) results.next();



				System.out.println("FOUND OBJECT : " + searchResult.getName());



				// Get a collection of the attributes that were returned

				// from the SearchResult.

				Attributes attrs = searchResult.getAttributes();



				if (attrs != null) {



					System.out.println("--> LASTNAME :  " + attrs.get("sn").get());

					System.out.println("--> FIRSTNAME:  " + attrs.get("givenName").get());

					System.out.println("--> EMAIL    :  " + attrs.get("mail").get());



				}



			}



			ctx.close();



		} catch (NamingException e) {

			e.printStackTrace();

		}

	}

}



~ Troy Campano ~


Reader's Comments - Add Comment


Find some of this content useful? Please consider a donation. Any donation is appreciated.