LDAP 查询获取一个组的所有组(嵌套)

4
我想列出Active Directory中的所有组,包括嵌套的。
使用这个命令,我可以获得顶级组:
try {
    Hashtable<String,String> props = new Hashtable<String,String>();
    props.put(Context.SECURITY_AUTHENTICATION, "simple");
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, "ldap://adserver");
    props.put(Context.SECURITY_PRINCIPAL, "user@domain");
    props.put(Context.SECURITY_CREDENTIALS, "password");

    DirContext ctx = new InitialDirContext(props);

    SearchControls cons = new SearchControls();
    cons.setReturningAttributes(new String[] {"cn"});
    cons.setSearchScope(SearchControls.ONELEVEL_SCOPE);

    NamingEnumeration<SearchResult> answer = ctx.search("cn=users,dc=domain,dc=com", "(objectcategory=group)", cons);
    System.out.println("AD GROUPS:");
    while(answer.hasMore()) {
        SearchResult result = (SearchResult) answer.next();
        Attributes atts = result.getAttributes();
        Attribute att = atts.get("cn");
        String groupName = (String)att.get();

        //how to search for groups nested in this group
    }
} catch (NamingException e) {
    e.printStackTrace();
}

我该如何获取嵌套组?我进行了一些谷歌搜索,并找到两种方法:

NamingEnumeration<SearchResult> nested = ctx.search("cn=users,dc=domain,dc=com", "(&(objectClass=group)(objectCategory=group)(memberOf:1.2.840.113556.1.4.194:=cn="+groupName+"))", controls);

并且

NamingEnumeration<SearchResult> nested = ctx.search("cn=users,dc=domain,dc=com", "(&(objectClass=group)(objectCategory=group)(memberOf=CN="+groupName+"))", controls);

但是这个方法没有返回嵌套组。我做错了什么?
6个回答

2

如果您想查找嵌套组,请确保Active Directory具有memberOf:1.2.840.113556.1.4.1941(请勿更改此神奇的数字字符串)。

(&(objectCategory=Person)(sAMAccountName=*)(memberOf:1.2.840.113556.1.4.1941:=CN=Test group,CN=Users,DC=domain,DC=net))

什么是魔术字符串?它是否始终适用于过去或未来的AD版本? - A N
你知道的,这是微软。将来总是不可预测的。到目前为止它在运作。根据 https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx "它仅适用于安装有Windows Server 2003 SP2或Windows Server 2008(或更高版本)的域控制器。" - FoxyBOA

1

你可以尝试做下一个

Attribute memberOf = srLdapUser.getAttributes().get("memberOf");
if (memberOf != null) {
  for (int i = 0; i < memberOf.size(); i++) {
      Attributes atts = ctx.getAttributes(memberOf.get(i).toString(), new String[] { "CN" });
      Attribute att = atts.get("CN");
      groups.add((att.get().toString())); 
  }
  System.out.println(groups.toString());`

0
在LDAP中,我们可以查询用户是否属于给定的组。一旦建立连接,您可以使用成员或memberOf属性进行查询。
查询memberOf属性: 使用的过滤器:(&(Group Member Attribute=Group DN)(objectClass=Group Object class)) 示例:(&(memberOf=CN=group,ou=qa_ou,dc=ppma,dc=org)(objectClass=group))
使用成员属性: 使用的过滤器:(&(Group Member Attribute=User DN)(objectClass=Group Object class)) 示例:(&(member=CN=user,ou=qa_ou,dc=ppma,dc=org)(objectClass=group))
但是,您需要使用成员或memberOf属性列表递归搜索用户。例如,如果用户具有以下组层次结构:
cn: user1 memberOf: CN=group1,DC=foo,DC=example,DC=com memberOf: CN=group2,DC=foo,DC=example,DC=com
那么您将需要使用额外的LDAP搜索递归查找group1和group2,以及这些组所属的组。

我们不能在生产环境中使用LDAP_MATCHING_RULE_IN_CHAIN,因为当我们有太深的嵌套层次时它无法工作,并且它仅适用于Active Directory。下面的解决方案可以独立地与AD或OpenLDAP一起使用,我们只需要替换组属性即可。

以下是查询用户所属的所有嵌套组的示例代码:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class MemberDemo {
    private static final String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
    private static final String connectionURL = "ldap://10.224.243.133:389";
    private static final String connectionName = "CN=administrator,CN=users,DC=ppma,DC=org";
    private static final String connectionPassword = "Conleyqa12345";

    public static int nestLevel = 3;
    public static int level = 1;

    // Optional
    private static final String authentication = null;
    private static final String protocol = null;
    private static String userBase = "OU=qa_OU,DC=ppma,DC=org";

    public static void main(String[] args) throws NamingException {
        long start = System.currentTimeMillis();

        Hashtable<String, String> env = new Hashtable<String, String>();

        // Configure our directory context environment.

        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
        env.put(Context.PROVIDER_URL, connectionURL);
        env.put(Context.SECURITY_PRINCIPAL, connectionName);
        env.put(Context.SECURITY_CREDENTIALS, connectionPassword);
        if (authentication != null)
            env.put(Context.SECURITY_AUTHENTICATION, authentication);
        if (protocol != null)
            env.put(Context.SECURITY_PROTOCOL, protocol);

        InitialDirContext context = new InitialDirContext(env);

        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);

        Set<String> traversedGroups = new HashSet<String>();
        Set<String> relatedGroups = new HashSet<String>();
        List<String> tempParentColl = new CopyOnWriteArrayList<String>();
        List<String> tempGroups = new ArrayList<String>();

        String loginUser = "CN=qa20Nest,OU=qa_OU,DC=ppma,DC=org";

        String filter = "(&(member=" + loginUser + ")(objectClass=group))";
        tempGroups = findNestedGroups(tempGroups, context, filter, loginUser, constraints,
                tempParentColl, traversedGroups, getUserName(loginUser));
        relatedGroups.addAll(tempGroups);

        System.out.println("Parent Groups :");

        for (String group : relatedGroups) {
            System.out.println(group);
        }
        long end = System.currentTimeMillis();
        long elapsedTime = end - start;
        System.out.println("Total time taken in sec : " + elapsedTime / 1000);

    }

    @SuppressWarnings("rawtypes")
    public static List<String> findNestedGroups(List<String> tempGrpRelations, InitialDirContext context, String filter,
            String groupName, SearchControls constraints, List<String> tempParentColl, Set<String> traversedGrp,
            String groupIdentifier) {
        NamingEnumeration results;
        try {
            traversedGrp.add(groupName);
            results = context.search(userBase, filter, constraints);

            // Fail if no entries found
            if (results == null || !results.hasMore()) {
                System.out.println("No result found for :" + groupName);
                if (tempParentColl.isEmpty()) {
                    return tempGrpRelations;
                } else {
                    tempParentColl.remove(groupName);
                }
            }

            while (results.hasMore()) {
                SearchResult result = (SearchResult) results.next();
                System.out.println("DN - " + result.getNameInNamespace());
                tempParentColl.add(result.getNameInNamespace());
                tempGrpRelations.add(result.getNameInNamespace());
            }

            Iterator<String> itr = tempParentColl.iterator();
            while (itr.hasNext()) {
                String groupDn = itr.next();
                String nfilter = "(&(member=" + groupDn + ")(objectClass=group))";
                tempParentColl.remove(groupDn);
                if (!traversedGrp.contains(groupDn)) {
                    findNestedGroups(tempGrpRelations, context, nfilter, groupDn, constraints, tempParentColl,
                            traversedGrp, getUserName(groupDn));
                }
            }

        } catch (NamingException e) {
            e.printStackTrace();
        }
        return tempGrpRelations;
    }

    public static String getUserName(String cnName) {

        String name = cnName.substring(cnName.indexOf("CN=")).split(",")[0].split("=")[1];
        return name;
    }
}

0

这对我有用。

(&(objectClass=group)(memberof:1.2.840.113556.1.4.1941:=" + groupDn + "))

什么是魔术字符串?它是否始终适用于过去或未来的AD版本? - A N

0

您可以按以下方式使用类别过滤器

(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))


2
嵌套组怎么办? - user207421

-1
尝试进行更改
cons.setSearchScope(SearchControls.ONELEVEL_SCOPE); 

cons.setSearchScope(SearchControls.SUBTREE_SCOPE);

这应该允许您搜索包括在内并且低于您指定的级别的整个子树


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接