2011-12-18 17 views
18

Estoy usando Weblogic, Ejb3.0. Java 1.6Cómo conectarme con Java en Active Directory

Necesito acceder a Active Directory a través del código Java. He leído sobre varias maneras (Kerberos, LDAP)

¿Alguien podría aconsejarme sobre la forma cómoda de hacerlo? donde podría tener algunos ejemplos de código completo,

gracias, ray.

+0

¿A qué desea acceder AD? Kerberos normalmente se limita a la autenticación (aunque los tickets Kerberos de AD también contienen algunas de sus propias extensiones, que pueden ser difíciles de leer desde Java). LDAP también puede realizar autenticación, pero también es un directorio con más información sobre el usuario. La principal diferencia es que puede usar Kerberos para SSO. – Bruno

+0

Sea más preciso lo que exactamente quiere. –

Respuesta

33

Aquí es un código simple que autenticar y realizar una búsqueda de LDAP usin JNDI en un W2K3:

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.PROVIDER_URL, "ldap://dom.fr:389"); 
     ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); 
     //ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr"); 
     ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=jean paul blanc,ou=MonOu,dc=dom,dc=fr"); 
     ldapEnv.put(Context.SECURITY_CREDENTIALS, "pwd"); 
     //ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl"); 
     //ldapEnv.put(Context.SECURITY_PROTOCOL, "simple"); 
     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=dom,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); 
    } 
    } 
} 
+0

Muchas gracias por este código agradable y fácil que es mucho mejor que otros desarrolladores –

11
+0

Entonces, ¿cuál debería decidir si uso LDAP o Kerberos? ¿Podría ser que el directorio activo al que intento acceder no admita Kerberos? – rayman

+0

Tengo poca familiaridad con Kerberos tbh. ¿Estás autenticando contra AD o haces más, como leer/escribir datos? Si en segundo lugar, probablemente LDAP, si primero, no estoy seguro. – clyfe

+1

@rayman: Kerberos se trata de autenticación y autorización. Si solo desea acceder a cierta información almacenada en un directorio, use LDAP. Su pregunta es un poco amplia, tal vez pueda describir sus requisitos. – home

Cuestiones relacionadas