如何在活动目录查询中获取用户组?

时间:2014-01-13 10:37:03

标签: java active-directory ldap

我在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);
    }
}

1 个答案:

答案 0 :(得分: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中的用户和群组一起玩!