检查广告组是否是另一个组的成员(递归)

时间:2019-06-19 10:41:33

标签: c# active-directory active-directory-group activedirectorymembership

想象我有结构

RootGroup <- Group{x} .... <- Group{x+n} <- Group100 

我如何检查Group100RootGroup的成员

我有这个,它总是返回false

private bool IsMemberOfInternal(string userOrGroupDistinguishedName, string groupMembershipDistinguishedName)
        {
            GroupPrincipal principal = null;
            GroupPrincipal target = null;
            try
            {
                principal = _getUserGroupPrincipalFunc(principalContext, userOrGroupDistinguishedName);
                target = _getUserGroupPrincipalFunc(principalContext, groupMembershipDistinguishedName);

                if (principal != default(GroupPrincipal)
                    && target != default(GroupPrincipal))
                {
                    return principal.IsMemberOf(target);
                }
            }
            catch
            {
            }

            return false;
        }

1 个答案:

答案 0 :(得分:1)

最好不要使用GroupPrincipal。实际上,AD具有一种内置的方式来执行这种搜索,其速度远远快于GroupPrincipal所能做的任何事情。您可以通过直接使用DirectoryEntryDirectorySearcher来使用它(无论如何,GroupPrincipalPrincipalSearcher都是在幕后使用的。)

我写了一篇文章,了解用户是否是特定组的成员,但是它对组也同样适用。我那里有一个sample method,您可以使用它:

private static bool IsUserInGroup(DirectoryEntry user, DirectoryEntry group, bool recursive) {

    //fetch the attributes we're going to need
    user.RefreshCache(new [] {"distinguishedName", "objectSid"});
    group.RefreshCache(new [] {"distinguishedName", "groupType"});

    //This magic number tells AD to look for the user recursively through any nested groups
    var recursiveFilter = recursive ? ":1.2.840.113556.1.4.1941:" : "";

    var userDn = (string) user.Properties["distinguishedName"].Value;
    var groupDn = (string) group.Properties["distinguishedName"].Value;

    var filter = $"(member{recursiveFilter}={userDn})";

    if (((int) group.Properties["groupType"].Value & 8) == 0) {
        var groupDomainDn = groupDn.Substring(
            groupDn.IndexOf(",DC=", StringComparison.Ordinal));
        var userDomainDn = userDn.Substring(
            userDn.IndexOf(",DC=", StringComparison.Ordinal));
        if (groupDomainDn != userDomainDn) {
            //It's a Domain Local group, and the user and group are on
            //different domains, so the account might show up as a Foreign
            //Security Principal. So construct a list of SID's that could
            //appear in the group for this user
            var fspFilters = new StringBuilder();

            var userSid =
                new SecurityIdentifier((byte[]) user.Properties["objectSid"].Value, 0);
            fspFilters.Append(
                $"(member{recursiveFilter}=CN={userSid},CN=ForeignSecurityPrincipals{groupDomainDn})");

            if (recursive) {
                //Any of the groups the user is in could show up as an FSP,
                //so we need to check for them all
                user.RefreshCache(new [] {"tokenGroupsGlobalAndUniversal"});
                var tokenGroups = user.Properties["tokenGroupsGlobalAndUniversal"];
                foreach (byte[] token in tokenGroups) {
                    var groupSid = new SecurityIdentifier(token, 0);
                    fspFilters.Append(
                        $"(member{recursiveFilter}=CN={groupSid},CN=ForeignSecurityPrincipals{groupDomainDn})");
                }
            }
            filter = $"(|{filter}{fspFilters})";
        }
    }

    var searcher = new DirectorySearcher {
        Filter = filter,
        SearchRoot = group,
        PageSize = 1, //we're only looking for one object
        SearchScope = SearchScope.Base
    };

    searcher.PropertiesToLoad.Add("cn"); //just so it doesn't load every property

    return searcher.FindOne() != null;
}

此方法还处理user(或您的子组)位于根组外部信任域中的情况。那可能不一定要担心。

只需为您的DirectoryEntry传递一个Group100作为user参数。像这样:

var isMemberOf = IsUserInGroup(
    new DirectoryEntry($"LDAP://{userOrGroupDistinguishedName}"),
    new DirectoryEntry($"LDAP://{groupMembershipDistinguishedName}"),
    true);

对于递归搜索(当您为true参数传递recursive时,它将使用LDAP_MATCHING_RULE_IN_CHAIN“匹配规则OID”(如here所述):

  

此规则仅限于适用于DN的过滤器。这是一个特殊的“扩展”匹配运算符,它将对象中的祖先链一直走到根,直到找到匹配项。