Check Active Membership in an Active Directory Group

So, I have a question regarding recursive groups in the active directory. I have a small method that checks if a user id is in a group or not. It works great. Today it turned out that he does not check for recursive group membership, and I'm not too sure how (or if) there is a way to do this. Here is what I'm still not recursive:

public static bool CheckGroupMembership(string userID, string groupName, string Domain) { bool isMember = false; PrincipalContext ADDomain = new PrincipalContext(ContextType.Domain, Domain); UserPrincipal user = UserPrincipal.FindByIdentity(ADDomain, userID); if (user.IsMemberOf(ADDomain, IdentityType.Name, groupName.Trim())) { isMember = true; } return isMember; } 

I saw something about a directory search engine or something like that, but I'm a little new to working with AD, and although I understand the concepts, some other things are still a bit lost for me.

Thanks!

+8
active-directory
source share
2 answers

Here is a solution using System.DirectoryServices.AccountManagement Namespace . This is a kind of recursive solution. In Find recursive group membership (Active Directory) using C # , I give a recursive solution that also works with distribution groups.

 /* Retreiving a principal context */ Console.WriteLine("Retreiving a principal context"); PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "PWD"); /* Look for all the groups a user belongs to */ UserPrincipal aUser = UserPrincipal.FindByIdentity(domainContext, "user1"); PrincipalSearchResult<Principal> a = aUser.GetAuthorizationGroups(); foreach (GroupPrincipal gTmp in a) { Console.WriteLine(gTmp.Name); } 
+13
source share

You can also check with the recursive option GroupPrincipal.GetMembers .

 public static bool CheckGroupMembership(string userID, string groupName, string Domain) { bool isMember = false; PrincipalContext ADDomain = new PrincipalContext(ContextType.Domain, Domain); UserPrincipal user = UserPrincipal.FindByIdentity(ADDomain, userID); GroupPrincipal group = GroupPrincipal.FindByIdentity(ADDomain, groupName); if ((user != null) && (group != null)) { isMember = group.GetMembers(true).Contains(user); } return isMember; } 
+19
source share

All Articles