2011-06-10 16 views
19

Kullanıcı kimliğini dn ve parola ile doğrulayabildiğim bir çalışma kod snippet'ım var. Benim şartım, kullanıcının kullanıcı adını (sAMAccountName) girmesi ve sAMAccountName ve şifresini kullanarak kimlik doğrulaması yapmak istemesidir. Bunu başarmak için bu kodu nasıl değiştirebilirim?Java LDAP kimlik doğrulaması

String userName = "John P R-Asst General Manager"; 
    String passWord = "asdfgh123"; 
    String base ="OU=SOU,DC=example,DC=com"; 
    String dn = "cn=" + userName + "," + base; 

    String ldapURL = "ldap://mdsdc3.example.com:389"; 
    authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); 
    authEnv.put(Context.PROVIDER_URL, ldapURL); 
    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); 
    authEnv.put(Context.SECURITY_PRINCIPAL, dn); 
    authEnv.put(Context.SECURITY_CREDENTIALS, password); 

    try { 
     DirContext authContext = new InitialDirContext(authEnv); 
     return true; 

    } catch (NamingException namEx) { 
     return false; 
    } 

cevap

2

böyle Context.PROVIDER_URL tamamlamaya çalışacağız Can: Ben GSSAPI kullanmak daha iyi olurdu düşünün

String ldapURL = "ldap://mdsdc3.example.com:389/DC=example,DC=com"; 

, belki bir umarım bu yardımcı olur here ve here

43

bakmak olabilir Birçoğunuz. Sen CN, DN ile tüm kullanıcı hiyerarşiye gerekmez

vb sadece domain \ kullanıcı ve şifre geçen giriş yapabilirsiniz

.

try 
    { 
     // Set up the environment for creating the initial context 
     Hashtable<String, String> env = new Hashtable<String, String>(); 
     env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); 
     env.put(Context.PROVIDER_URL, "ldap://ldap_server:389"); 
     // 
     env.put(Context.SECURITY_AUTHENTICATION, "simple"); 
     env.put(Context.SECURITY_PRINCIPAL, "domain\\user"); //we have 2 \\ because it's a escape char 
     env.put(Context.SECURITY_CREDENTIALS, "test"); 

     // Create the initial context 

     DirContext ctx = new InitialDirContext(env); 
     boolean result = ctx != null; 

     if(ctx != null) 
      ctx.close(); 

     return result; 
    } 
    catch (Exception e) 
    {   
     return false; 
    } 
:

Ben feryat olduğu gibi benim kod çalışıyor ettik