Search code examples
c#asp.netrecursionactive-directoryactive-directory-group

How I can make a recursiv search in ad with a User whether this is in a group or subgroup?


Hi I use the Active Directory and C# in a ASP.NET Application and I want that I get a bool if a User is in a Group or in this SubGroups. I have write a method that get me whether th user is in the group but not in this Subgroups :(

How I can make a recursiv search in my method:

here my code:

public static bool IsUserInGroup(string dc, string User, string group) 
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc);

            GroupPrincipal p = GroupPrincipal.FindByIdentity(ctx, group);

            UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, User);

            bool isMember = u.IsMemberOf(p); 

            return isMember; 
        }

static void Main(string[] args)
        {
            string dc = "company.com";
            string user = "test.w";

            bool isadmin = IsUserInGroup(dc, user, "TAdmin");
            bool isUser = IsUserInGroup(dc, user, "TUser");

            Console.WriteLine("Admin: " + isadmin);
            Console.WriteLine("User: " + isUser);

            Console.ReadLine();

        }

Solution

  • Instead of IsMemberOf method you should use GetMembers(Boolean) with 'true'. It will return all the members of the group - even nested. Then make a loop to check if your user principle is in the result. Check this link.

    Additional note: try such code

    public static bool IsUserInGroup(string dc, string User, string group) 
    {
        bool found = false;
    
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc);
        GroupPrincipal p = GroupPrincipal.FindByIdentity(ctx, group);
        UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, User);
    
        found = p.GetMembers(true).Contains(u);
    
        p.Dispose();
        u.Dispose();
    
        return found; 
    }