在C#中仅搜索指定组中的Active Directory用户

本文关键字:Active Directory 用户 搜索 | 更新日期: 2023-09-27 17:58:10

我一直在努力寻找一种查询指定AD组成员的好方法。

我在查找组,甚至根据条件查询用户方面都没有问题。

目前我有

 PrincipalContext context = new PrincipalContext(ContextType.Domain, _domain, ADServerUser, ADServerPassword);
 UserPrincipal userPrinciple = new UserPrincipal(context);
 userPrinciple.GivenName = "stringToSearchForFirstName";
 userPrinciple.Name = "stringToSearchForUserName";
 userPrinciple.Surname = "stringToSearchForLastName";
 PrincipalSearcher srch = new PrincipalSearcher(new UserPrincipal(context));                    
 srch.QueryFilter = userPrinciple;
 var result = srch.FindAll();

这给了我想要的所有用户,但它不会过滤掉组。

我可以将GroupPrinciple对象与主体搜索一起使用,但无法过滤掉Users。

我有点想要一种能够同时应用UserPrincipal和GroupPrincipal来通过组和用户参数过滤返回结果的方法。

我使用了linqwhere子句来尝试进行匹配,以查看用户是否在一个组中,但当我获得所有用户时,查询超时。总的来说是有道理的。

但是,如果我查询出组,我就无法使用principalSearcher来应用查询。

有什么想法吗?

在C#中仅搜索指定组中的Active Directory用户

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, _domain);
// get the AD Group you are wanting to Query
GroupPrincipal group = GroupPrincipal.FindByIdentity("cn=YourGroupname");
foreach(Principal p in group.Members)
{
    //do what ever coding you need to do here            
}

根据我的研究,我得出结论,使用Principal对象来过滤组和用户参数是不可能的。我们需要恢复使用AD的查询字符串方法来解决这个问题。