检查嵌套AD组中的用户成员身份

cor*_*010 3 c# asp.net-mvc directoryservices active-directory

我有一个带有以下函数的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);
}
Run Code Online (Sandbox Code Playgroud)

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

希望获得帮助来修复此代码,以便通过组内的每个嵌套组递归地检查成员资格.我查看了StackOverflow中类似问题的答案,但无法弄清楚如何最好地修改我的函数以使其工作.

谢谢.

Ash*_*ore 10

这就是你想要的:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)