【问题标题】:Checking for User Membership in Nested AD Groups检查嵌套 AD 组中的用户成员资格
【发布时间】:2023-09-16 16:16:01
【问题描述】:

我有一个 ASP.NET Framework 4.5 应用程序,它具有以下功能来检查用户是否是 AD 组的成员:

public static bool IsUserGroupMember(string userName, string groupName)
{
    string domain = "ad.our.org";
    string defaultOU = "OU=Our_Department,DC=ad,DC=our,DC=org";
    PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain, defaultOU, ContextOptions.SimpleBind);
    UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName);
    GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, groupName);

    return oGroupPrincipal.Members.Contains(oUserPrincipal);
}

但是,这仅在用户直接是该组的成员而不是嵌套在该组中的另一个组的成员时才有效。

希望得到修复此代码的帮助,以通过组内的每个嵌套组递归检查成员资格。我在 * 中查看了类似问题的答案,但不知道如何最好地修改我的函数以使其正常工作。

谢谢。

【问题讨论】:

标签: c# asp.net-mvc active-directory directoryservices


【解决方案1】:

这就是你想要的:

public static bool IsUserGroupMember(string userName, string groupName)
{
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context, userName))
    using (PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups())
    {
        return groups.OfType<GroupPrincipal>().Any(g => g.Name.Equals(groupName, StringComparison.OrdinalIgnoreCase));
    }
}

【讨论】:

  • 感谢您的快速回复,Ashigore。但我收到错误消息:DirectoryServices.AccountManagement.Principal 不包含“OfType”的定义?
  • @corix010 您需要包含 System.Linq 命名空间。
  • @Antoops 这绝对给出了正确的输出。这不会显示通讯组。
  • @Ashigore 我得到了这个*.com/questions/5312744/…的输出