Aller au contenu | Aller au menu | Aller à la recherche


LDAP JAVA

Besoin de communiquer avec un annuaire LDAP en JAVA ?

Programmer en JAVA pour communiquer avec LDAP

Connexion et recherche dans un annuaire LDAP en JAVA

package com.placeoweb;
 
import java.util.Enumeration;
import java.util.Hashtable;
 
import javax.naming.Context;
import javax.naming.NamingEnumeration;
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;
 
public class Ldap {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
 
		DirContext ldapContext = null;
		String ldap_server = "127.0.0.1:389";
		String global_dc = "dc=placeoweb"; // ton_dc à changer
		String ou_dn = "ou=ton_ou," + global_dc; // ton_ou à changer, en fonction de l'architecture de ton annuaire
 
		String admin_dn = "cn=" + getUserName() + "," + global_dc; // Identifiant de connexion à l'annuaire
		String admin_pwd = getPassword();
		String user_uid = "user_a_tester"; // Identifiant à tester dans l'annuaire
		String user_pwd = "pass_a_tester";
		String user_dn = "uid=" + user_uid + "," + ou_dn;
 
		try {
			// http://docs.oracle.com/javase/7/docs/technotes/guides/jndi/jndi-ldap.html
//			3.1 JNDI Properties
//			The LDAP service provider supports the following JNDI environment properties:
//			 
//			Property 	Supported 	Comments
//			java.naming.batchsize 	Yes 	Default value is 1.
//			java.naming.factory.control 	Yes 	 
//			java.naming.factory.initial 	Yes 	Specify com.sun.jndi.ldap.LdapCtxFactory to use the LDAP service provider as the initial context.
//			java.naming.factory.object 	Yes 	 
//			java.naming.factory.state 	Yes 	 
//			java.naming.language 	No 	Ignored by the provider.
//			java.naming.provider.url 	Yes 	On systems earlier than the Java 2 SDK, v 1.4.1, can contain only a single URL. On systems earlier than the Java 2 SDK, v 1.4.2, cannot contain LDAPS URLs.
//			java.naming.referral 	Yes 	 
//			java.naming.security.authentication 	Yes 	simple, none, list of SASL mechanisms
//			java.naming.security.credentials 	Yes 	 
//			java.naming.security.principal 	Yes 	 
 
 
			Hashtable<String, String> ldapEnv = new Hashtable<String, String>();
			ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
			ldapEnv.put(Context.PROVIDER_URL, "ldap://" + ldap_server);	// localhost:389
			ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");		// simple, none, list of SASL mechanisms
			ldapEnv.put(Context.SECURITY_PRINCIPAL, admin_dn);			// cn=admin,dc=placeoweb
			ldapEnv.put(Context.SECURITY_CREDENTIALS, admin_pwd);		// motdepasse
//			ldapEnv.put(Context.SECURITY_PRINCIPAL, user_dn);
//			ldapEnv.put(Context.SECURITY_CREDENTIALS, user_pwd);
			// ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
 
			// Connexion LDAP anomymous sans cyptage
//			ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
//			ldapEnv.put(Context.PROVIDER_URL, "ldap://" + ldap_server);	// localhost:389
//			ldapEnv.put(Context.SECURITY_AUTHENTICATION, "none");		// simple, none, list of SASL mechanisms
 
			// Connexion LDAP connecté en utilisateur admin et sans cyptage
//			ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
//			ldapEnv.put(Context.PROVIDER_URL, "ldap://" + ldap_server);	// localhost:389
//			ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");		// simple, none, list of SASL mechanisms
//			ldapEnv.put(Context.SECURITY_PRINCIPAL, admin_dn);			// cn=admin,dc=placeoweb
//			ldapEnv.put(Context.SECURITY_CREDENTIALS, admin_pwd);		// motdepasse		
 
			ldapContext = new InitialDirContext(ldapEnv);
			System.out.println("LDAP : Bind Ok = " + user_uid);
 
			 // Recherche en profondeur
			 // http://www.dil.univ-mrs.fr/~massat/ens/jee/ldap.html
			 SearchControls controle = new SearchControls();
			 controle.setSearchScope(SearchControls.SUBTREE_SCOPE);
 
//			 String critere = "(|(sn=premier)(sn=deux*))";
//			 String critere = "(cn = *)";	// ne trouve rien
			 String critere = "(cn=*)";		// ok					ldapsearch -x -h localhost -b 'dc=placeoweb' '(cn=*)'  
//			 DirContext ictx = new InitialDirContext(ldapEnv);
//			 NamingEnumeration<SearchResult> e = ldapContext.search("ou=monorganisationunit,dc=placeoweb", critere, controle);
			 NamingEnumeration<SearchResult> e = ldapContext.search("dc=devel", critere, controle);
			 while (e.hasMore()) {
				 SearchResult r = e.next();
				 System.out.println("name: " + r.getName());
				 System.out.println("object: " + r.getClassName());
 				 System.out.println("getAttributes: " + r.getAttributes());
 
 				 listerAttributs(r.getAttributes());
			 }
 
			ldapContext.close();
		} catch (Exception e) {
			System.out.println("LDAP : Bind Error = " + e);
		}
 
	}
 
	public static void listerAttributs(Attributes atts) {
		try {
			for (NamingEnumeration e = atts.getAll(); e.hasMore();) {
				Attribute a = (Attribute) e.next();
				System.out.println(a.getID() + ":");
				Enumeration values = a.getAll();
				while (values.hasMoreElements()) {
					System.out.println("valeur : " + values.nextElement().toString());
				}
			}
		} catch (javax.naming.NamingException e) {
			System.out.println(e.getMessage());
		}
	}
 
}

Changer sous LDAP le mot de passe en MD5

BasicAttribute newAtt = new BasicAttribute("userPassword", digestMd5(passClear) );
 
        ModificationItem[] modItems = new ModificationItem[1];
        modItems[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, newAtt);
 
        dirContext().modifyAttributes(dn, modItems);
 
	/**
	 * String to MD5 4 LDAP (qui fonctionne !)
	 * @param password
	 * @return
	 */
	private String digestMd5(final String password) {
		System.out.println("digestMd5(final String password)");
		String base64;
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(password.getBytes());
			base64 = new BASE64Encoder().encode(digest.digest());
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		return "{MD5}" + base64;
	}

Ressources

Ajouter un commentaire

Le code HTML est affiché comme du texte et les adresses web sont automatiquement transformées.

Fil des commentaires de ce billet