Check active directory group membership recursively

为君一笑 提交于 2019-12-03 12:16:17
JPBlanc

Here is a solution using System.DirectoryServices.AccountManagement Namespace. It's 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);    
}

You can also check by using the recursive option of 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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!