首页 > 解决方案 > 如何在 .net 中获取 ForeignSecurityPrincipal 对象的详细信息

问题描述

我有 2 个域 A 和 B。我在 B“GroupInB”中有一个组,其中有一个用户“UserInB”(将来,该组中可以有很多用户)。在域 A 中,我创建了一个组“GroupInA”,然后将“GroupInB”添加到“GroupInA”。(这会导致 GroupB 的 ForeignSecurityPrincipal)。而且我还在“GroupA”中添加了一个用户“UserInA”。

现在的问题是,我想读取“GroupA”中的所有用户。我希望结果是

  1. 用户InA
  2. 用户InB

但是当试图从 DirectoryEntry 读取用户时,我得到的只是

  1. 用户InA
  2. GroupInB

有什么方法可以让我也从“GroupInB”获取用户?:(

标签: .netactive-directorycross-browserdomaincontroller

解决方案


前段时间写了一篇关于获取群组所有成员的文章:查找群组的所有成员

我包括了关于从外部受信任域中查找用户的部分,它显示为外部安全主体,但是我似乎忘记了这个特定的用例:来自外部域的组是成员。所以我更新了我文章中的代码并将其包含在下面。

这有点复杂,因为 Foreign Security Principal 具有外部域上对象的 SID,但是要使用 SID 绑定到对象,您必须使用域的 DNS 名称。因此,我们首先需要为所有受信任的域创建域 SID 和 DNS 名称的映射。但是,如果您只在一个环境中运行它,您总是可以硬编码一个域列表以加快速度。

这是代码。如果您传递参数truerecursive它将展开所有成员组。

public static IEnumerable<string> GetGroupMemberList(DirectoryEntry group, bool recursive = false, Dictionary<string, string> domainSidMapping = null) {
    var members = new List<string>();

    group.RefreshCache(new[] { "member", "canonicalName" });

    if (domainSidMapping == null) {
        //Find all the trusted domains and create a dictionary that maps the domain's SID to its DNS name
        var groupCn = (string) group.Properties["canonicalName"].Value;
        var domainDns = groupCn.Substring(0, groupCn.IndexOf("/", StringComparison.Ordinal));

        var domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, domainDns));
        var trusts = domain.GetAllTrustRelationships();

        domainSidMapping = new Dictionary<string, string>();

        foreach (TrustRelationshipInformation trust in trusts) {
            using (var trustedDomain = new DirectoryEntry($"LDAP://{trust.TargetName}")) {
                try {
                    trustedDomain.RefreshCache(new [] {"objectSid"});
                    var domainSid = new SecurityIdentifier((byte[]) trustedDomain.Properties["objectSid"].Value, 0).ToString();
                    domainSidMapping.Add(domainSid, trust.TargetName);
                } catch (Exception e) {
                    //This can happen if you're running this with credentials
                    //that aren't trusted on the other domain or if the domain
                    //can't be contacted
                    throw new Exception($"Can't connect to domain {trust.TargetName}: {e.Message}", e);
                }
            }
        }
    }

    while (true) {
        var memberDns = group.Properties["member"];
        foreach (string member in memberDns) {
            using (var memberDe = new DirectoryEntry($"LDAP://{member.Replace("/", "\\/")}")) {
                memberDe.RefreshCache(new[] { "objectClass", "msDS-PrincipalName", "cn" });

                if (recursive && memberDe.Properties["objectClass"].Contains("group")) {
                    members.AddRange(GetGroupMemberList(memberDe, true, domainSidMapping));
                } else if (memberDe.Properties["objectClass"].Contains("foreignSecurityPrincipal")) {
                    //User is on a trusted domain
                    var foreignUserSid = memberDe.Properties["cn"].Value.ToString();
                    //The SID of the domain is the SID of the user minus the last block of numbers
                    var foreignDomainSid = foreignUserSid.Substring(0, foreignUserSid.LastIndexOf("-"));
                    if (domainSidMapping.TryGetValue(foreignDomainSid, out var foreignDomainDns)) {
                        using (var foreignMember = new DirectoryEntry($"LDAP://{foreignDomainDns}/<SID={foreignUserSid}>")) {
                            foreignMember.RefreshCache(new[] { "msDS-PrincipalName", "objectClass" });
                            if (recursive && foreignMember.Properties["objectClass"].Contains("group")) {
                                members.AddRange(GetGroupMemberList(foreignMember, true, domainSidMapping));
                            } else {
                                members.Add(foreignMember.Properties["msDS-PrincipalName"].Value.ToString());
                            }
                        }
                    } else {
                        //unknown domain
                        members.Add(foreignUserSid);
                    }
                } else {
                    var username = memberDe.Properties["msDS-PrincipalName"].Value.ToString();
                    if (!string.IsNullOrEmpty(username)) {
                        members.Add(username);
                    }
                }
            }
        }

        if (memberDns.Count == 0) break;

        try {
            group.RefreshCache(new[] {$"member;range={members.Count}-*"});
        } catch (COMException e) {
            if (e.ErrorCode == unchecked((int) 0x80072020)) { //no more results
                break;
            }
            throw;
        }
    }
    return members;
}

推荐阅读