Checking for User Membership in Nested AD Groups

corix010 picture corix010 · Mar 7, 2014 · Viewed 7.1k times · Source

I have an ASP.NET Framework 4.5 app with the following function to check if user is a member of an AD group:

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);
}

However, this only works when the user is directly a member of the group and not a member of another group nested within this group.

Hope to get help fixing this code to check membership recursively through every nested group within the group. I looked at answers to similar issues in StackOverflow but can't figure out how to best modify my function to make it work.

Thanks.

Answer

Ashigore picture Ashigore · Mar 7, 2014

This is what you want:

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));
    }
}