| 12
 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
 
 | public class TestAD {
static DirContext ldapContext;
  public static void main (String[] args) throws NamingException
  {
    try
    {
      System.out.println("Début du test Active Directory");
 
      Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
      ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      ldapEnv.put(Context.PROVIDER_URL,  "ldap://societe.fr:389");
      ldapEnv.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5");
      ldapEnv.put("java.naming.security.sasl.realm","myRealm");
      ldapEnv.put("javax.security.sasl.qop", "auth");
      ldapEnv.put("javax.security.sasl.strength","high");
      ldapEnv.put(Context.SECURITY_PRINCIPAL, "dn:cn=administrateur,ou=users,o=societe.fr");
      ldapEnv.put(Context.SECURITY_CREDENTIALS,"myPassword");
 
 
      ldapContext = new InitialDirContext(ldapEnv);
 
      // Create the search controls         
      SearchControls searchCtls = new SearchControls();
 
      //Specify the attributes to return
      String returnedAtts[]={"sn","givenName", "samAccountName"};
      searchCtls.setReturningAttributes(returnedAtts);
 
      //Specify the search scope
      searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
 
      //specify the LDAP search filter
      String searchFilter = "(&(objectClass=user))";
 
      //Specify the Base for the search
      String searchBase = "dc=societe,dc=fr";
      //initialize counter to total the results
      int totalResults = 0;
 
      // Search for objects using the filter
      NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);
 
      //Loop through the search results
      while (answer.hasMoreElements())
      {
        SearchResult sr = (SearchResult)answer.next();
 
        totalResults++;
 
        System.out.println(">>>" + sr.getName());
        Attributes attrs = sr.getAttributes();
        System.out.println(">>>>>>" + attrs.get("samAccountName"));
      }
 
      System.out.println("Total results: " + totalResults);
      ldapContext.close();
    }
    catch (Exception e)
    {
      System.out.println(" Search error: " + e);
      e.printStackTrace();
      System.exit(-1);
    }
  }} | 
Partager