C# - GroupPrincipal.GetMembers(true) - 哪个组?

dot*_*emy 5 c# directoryservices active-directory

所以我试图通过递归枚举AD组成员资格来实现目标.目前我有......

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mine.domain.com");
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "myADGroup");
if (grp != null)
{
    foreach (Principal p in grp.GetMembers(true))
    {
        Console.WriteLine(p.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,这一切都很有效.它列出了作为组成员的每个用户以及嵌套在其中的组成员的所有用户,但可能存在很多嵌套级别.哪个好.

我真正需要的是要知道什么样的用户来自何处组在这个小巢.

GRP-MainProject
   -- GRP-Producers
   -- GRP-Artists
     -- UserA
Run Code Online (Sandbox Code Playgroud)

针对GRP-MainProject运行我当前的查询将返回UserA - 我应该如何返回用户以及他继承GRP-MainProject成员资格的GRP-Artists这一事实?

UserA是大约40个团体的成员,如果重要的话.编辑 - 值得一提的是,用户可以拥有来自多个嵌套组的成员资格.

任何想法将不胜感激.

ran*_*dcd 4

也许尝试这样的事情:

声明组对象的静态列表(GroupPrincipal 的简单类、整数级别和父 GroupPrincipal)

public class SomeDirTraverser
{
    private static List<GroupObj> _groups = new List<GroupObj>();

    public List<string> GetMembershipWithPath(string groupname)
    {
        List<string> retVal = new List<string>();

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupname);
        if (grp != null)
        {
            BuildHList(grp, 0, null);
            foreach (UserPrincipal usr in grp.GetMembers(true))
                retVal.Add(GetMbrPath(usr));
        }

        return retVal;
    }

    private void BuildHList(GroupPrincipal node, int level, GroupPrincipal parent)
    {
        PrincipalSearchResult<Principal> rslts = node.GetMembers();
        _groups.Add(new GroupObj() { Group = node, Level = level, Parent = parent });
        foreach (GroupPrincipal grp in rslts.Where(g => g is GroupPrincipal))
            BuildHList(grp, level + 1, node);
    }

    private string GetMbrPath(UserPrincipal usr)
    {
        Stack<string> output = new Stack<string>();
        StringBuilder retVal = new StringBuilder();
        GroupObj fg = null, tg = null;
        output.Push(usr.Name);
        foreach (GroupObj go in _groups)
        {
            if (usr.IsMemberOf(go.Group))
            {
                output.Push(go.Group.Name);
                fg = go;
                while (fg.Parent != null)
                {
                    output.Push(fg.Parent.Name);
                    tg = (from g in _groups where g.Group == fg.Parent select g).FirstOrDefault();
                    fg = tg;
                }
                break;
            }
        }
        while (output.Count > 1)
            retVal.AppendFormat("{0} ->", output.Pop());
        retVal.Append(output.Pop());

        return retVal.ToString();
    }
}

public class GroupObj
{
    public GroupPrincipal Group { get; set; }
    public int Level { get; set; }
    public GroupPrincipal Parent { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这个看起来应该能给你你想要的。