2015-12-12 71 views
0

公共靜態無效的主要(字串[] args){連接到組織的ACTVIE目錄

String domain="xyz.domain.com"; 
     String ldapHost="ldap://xyz.domain.com:389"; 
     String searchBase = "cn=users,dc=dom,dc=com"; 
     Scanner sn=new Scanner(System.in); 
     String user=sn.next(); 
     String password=sn.next(); 
     String returnedAtts[] ={ "sn", "givenName", "mail" }; 
     String searchFilter = "(&(objectClass=user)(sAMAccountName=" + user + "))"; 

     //Create the search controls 
     SearchControls searchCtls = new SearchControls(); 
     searchCtls.setReturningAttributes(returnedAtts); 

     //Specify the search scope 
     searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); 

     Hashtable env = new Hashtable(); 
     env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); 
     env.put(Context.PROVIDER_URL, ldapHost); 

     env.put(Context.SECURITY_AUTHENTICATION, "simple"); 

     env.put(Context.SECURITY_PRINCIPAL, user + "@" + domain); 

     env.put(Context.SECURITY_CREDENTIALS, password); 

     LdapContext ctxGC = null; 
     boolean ldapUser = false; 

     try 
     { 
      ctxGC = new InitialLdapContext(env, null); 

      //Search objects in GC using filters 
      NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls); 

      while (answer.hasMoreElements()) 
      { 
        SearchResult sr = (SearchResult) answer.next(); 
        Attributes attrs = sr.getAttributes(); 
        Map amap = null; 
        if (attrs != null) 
        { 
         amap = new HashMap(); 
         NamingEnumeration ne = attrs.getAll(); 
         while (ne.hasMore()) 
         {  
           Attribute attr = (Attribute) ne.next(); 
           amap.put(attr.getID(), attr.get()); 
           ldapUser = true; 

         } 
         ne.close(); 
        } 

      } 
      if(ldapUser=true) 
      { 

      } 
      else{ 

      } 

     } 
     catch (NamingException ex) 
     { 
      ex.printStackTrace(); 

     } 

我只需要用戶和口令認證。但無法弄清楚問題所在。我應該添加安全協議(ssl/tls)嗎?每當我在服務器上運行它時,javx.Nmaing.AuthenticationException會彈出?我無法做任何事情。把我趕出去。 謝謝!

+0

如果你a)更多地格式化了你的代碼,並且b)給了我們確切的例外,它將會有所幫助。可以忽略用戶名,但Exception提供了可能有所幫助的詳細信息 – Jan

回答

0

你的問題可能是這一行:

env.put(Context.SECURITY_PRINCIPAL, user + "@" + domain);

你正在構建一個用戶名,可能是無效的。爲此,用戶的userPrincipalName需要匹配user + "@" + domain。嘗試僅使用user