Lightweight Directory Access Protocol (LDAP)

Exemples

Exemple avec Java, en utilisant JNDI

Dans cet exemple, nous allons :

Le code de cet exemple est le suivant :

package fr.umlv.ig2k.demo;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

/**
 * Simple LDAP-JNDI Demo.
 * 
 * @author Vivien Boistuaud
 */
public class LDAPJNDIDemo {

	private DirContext ldapContext;
	
	public static void main(String[] args) {
		LDAPJNDIDemo demo = new LDAPJNDIDemo();
		try {
			demo.connect("ldap://localhost:10389", "uid=admin,ou=system", "secret");
		} catch (NamingException e) {
			System.err.println("Connection failed: " + e.getMessage());
			return;
		}
		try {
			NamingEnumeration<SearchResult> res =
				demo.search("ou=users,dc=example,dc=com",
					"(objectClass=inetOrgPerson)",
					new String[] { "uid", "mail" });

			while (res.hasMoreElements()) {
				SearchResult result = res.nextElement();
				System.out.println("Entry: DN=" + result.getName());
				Attributes attr = result.getAttributes();
				NamingEnumeration<? extends Attribute> attribueEnum = attr.getAll();
				while (attribueEnum.hasMoreElements()) {
					Attribute att = attribueEnum.nextElement();
					System.out.println(att.getID() + " = " + att.size() + " value(s)");
					for (int i=0; i < att.size(); ++i) {
						System.out.println("==> " + att.get(i));
					}
				}
			}
		} catch (NamingException e) {
			System.err.println("Error :" + e.getMessage());
			try {
				demo.disconnect();
			} catch (NamingException ne) {
				// Silently discarded, cannnot do anything if we cannt close connection
			}
		}
	}
	
	public void connect(String url, String userDN, String passwd) throws NamingException {
		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, url);                 // LDAP Server URL (ldaps for SSL implicit encryption)
		env.put(Context.SECURITY_AUTHENTICATION, "simple"); // Authentication type, can be SASL
		env.put(Context.SECURITY_PRINCIPAL, userDN);        // specify the username
		env.put(Context.SECURITY_CREDENTIALS, passwd);      // specify the password

		/*
		 * Executing this command will do the connect and bind operations,
		 * and a NamingException will be thrown if credentials are incorrect.
		 */
		ldapContext = new InitialDirContext(env);
	}
	
	public void disconnect() throws NamingException {
		ldapContext.close();
	}
	
	public NamingEnumeration<SearchResult> search(String base, String searchString, String[] returningAttributes) throws NamingException {
		SearchControls ctrl = new SearchControls();
		if (returningAttributes != null) {
			ctrl.setReturningAttributes(returningAttributes);
		}
		return ldapContext.search(base, searchString, ctrl);
	}
	
}
				

Exemple avec Java, en utilisant l'API jldap de Novell

Le même exemple que précédemment, mais avec JLDAP de Novell.

package fr.umlv.ig2k.demo;

import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPAttributeSet;
import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPSearchResults;

public class JLDAPDemo {

	public static void main(String[] args) {
		LDAPConnection ldapConnection = new LDAPConnection();
		try {
			ldapConnection.connect("localhost", 10389);
			ldapConnection.bind(LDAPConnection.LDAP_V3, "uid=admin,ou=system",
					"secret".getBytes());
			LDAPSearchResults results = ldapConnection.search(
					"ou=users,dc=example,dc=com", LDAPConnection.SCOPE_SUB,
					"(objectClass=inetOrgPerson)",
					new String[] { "uid", "mail" }, false);
			while (results.hasMore()) {
				LDAPEntry entry = results.next();
				System.out.println("Entry DN:" + entry.getDN());
				System.out.println("Attributes :");
				LDAPAttributeSet set = entry.getAttributeSet();
				for (Object attObject : set) {
					LDAPAttribute att = (LDAPAttribute) attObject;
					String[] values = att.getStringValueArray();
					System.out.println(" Att. " + att.getName() + " has "
							+ values.length + " value(s)");
					for (int i = 0; i < values.length; ++i) {
						System.out.println("  --- " + values[i]);
					}
				}
			}
		} catch (LDAPException e) {
			System.err.println("Error : " + e.getMessage());
		} finally {
			try {
				ldapConnection.disconnect();
			} catch (LDAPException e) {
				// Ignore this error safely in our case...
			}
		}

	}

}