2014-01-13 70 views
0

我在Windows Server 2012中安裝活動目錄並定義任何用戶。 如何獲取活動目錄查詢中的用戶組? 用戶是管理員組的成員。 如何在搜索中實現?如何獲取活動目錄查詢中的用戶組?

public static void main(String[] args) throws NamingException { 
    try { 
     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://192.168.1.51:389"); 
     ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); 
     ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=reza2,ou=test,dc=domain,dc=ir"); 
     ldapEnv.put(Context.SECURITY_CREDENTIALS, "pass"); 
     ldapContext = new InitialDirContext(ldapEnv); 
     SearchControls searchCtls = new SearchControls(); 
     String returnedAtts[] = {"samAccountName"; 
     searchCtls.setReturningAttributes(returnedAtts); 
     searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); 
     String searchFilter = "(&(objectClass=User))"; 
     String searchBase = "dc=domain,dc=ir"; 
     int totalResults = 0; 
     NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls); 
     while (answer.hasMoreElements()) { 
      SearchResult sr = answer.next(); 
      String dn = sr.getName() + ", " + searchBase; 
      totalResults++; 
      Attributes attrs = ldapContext.getAttributes(dn, returnedAtts); 

      for (int i = 0; i < returnedAtts.length; i++) { 
       Attribute attr = attrs.get(returnedAtts[i]); 
       if (attr == null) { 
        continue; 
       } 
       System.out.println(returnedAtts[i] + ":"); 
       for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { 
        System.out.println("\t" + vals.nextElement()); 

       } 
      } 
     } 

     System.out.println("Total results: " + totalResults); 
     ldapContext.close(); 
    } catch (Exception e) { 
     System.out.println(" Search error: " + e); 
     e.printStackTrace(); 
     System.exit(-1); 
    } 
} 

回答

0

您是否真的需要使用這種非常低級別的LDAP方法?

如果您使用的是.NET 3.5及更高版本,則應檢查System.DirectoryServices.AccountManagement(S.DS.AM)命名空間。在這裏閱讀全部內容:

基本上,你可以定義域範圍內,並可以輕鬆地查找用戶和/或組AD:

// set up domain context 
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "yourDomain", username, password)) 
{ 
    // find a user 
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName"); 

    if(user != null) 
    { 
     // get groups for user 
     var groups = user.GetGroups(); 

     foreach(Principal group in groups) 
     { 
      // do something with the groups 
     } 
    } 
} 

的新的S.DS.AM可以很容易地與AD中的用戶和羣組玩耍!

相關問題