1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| package fr.uce.dao.ldap;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
public class LDAPConnexion {
private DirContext dctx = null;
String ctxFact = "com.sun.jndi.ldap.LdapCtxFactory";
String ldapUrl = "ldap://ca.sociéte.fr:389";
private String baseRecherche = "ou=People,dc=sociéte ,dc=fr";
public LDAPConnexion() {
}
private void initContext() throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, ctxFact);
env.put(Context.PROVIDER_URL, ldapUrl);
this.dctx = new InitialDirContext(env);
}
/**
* Permet de test la connexion a ldap
*/
public void testConnectionLdap() {
try {
this.initContext();
SearchControls sc = new SearchControls();
String[] attributeFilter = { "uid", "userPassword" };
sc.setReturningAttributes(attributeFilter);
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "objectclass=inetorgperson";
// NamingEnumeration results = dctx.search(base, filter, sc);
NamingEnumeration<SearchResult> results = dctx.search(
baseRecherche, filter, sc);
dctx.close();
if (results.hasMore()) {
System.out
.println("la recherche à retourner un nombre de resultat != 0");
} else {
System.out.println("Nombre de personne dans ldap : 0");
;
}
} catch (NamingException e) {
System.out.println("impossible d'initialiser le context ");
e.printStackTrace();
}
}
/**
* Permet de verifier que l'utilisateur est enregistré dans l'annnuaire ldap
*
* @param login
* @param password
* @return
* @throws LdapException
* @throws NamingException
*/
public boolean authentifier(String login, String password)
throws NamingException {
this.initContext();
SearchControls sc = new SearchControls();
String[] attributeFilter = { "givenName" };
sc.setReturningAttributes(attributeFilter);
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
// String filter = "(&(uid=gfd)(userPassword=1234))";
StringBuilder filter = new StringBuilder();
filter.append("(&(uid=");
filter.append(login + ")");
filter.append("(userPassword:=");
filter.append(password + "))");
// NamingEnumeration results = dctx.search(base, filter, sc);
NamingEnumeration<SearchResult> results = dctx.search(baseRecherche,
filter.toString(), sc);
dctx.close();
if (results.hasMore()) {
return true;
} else {
return false;
}
}
} |
Partager