如何使用LDAP查找特定部门中的用户列表

时间:2014-01-20 05:24:14

标签: asp.net active-directory ldap directoryservices directorysearcher

如何使用DirectorySearcher和Filter / PropertiesToLoad获取特定部门中所有用户的列表?

我知道如何使用用户名进行过滤并获取用户的部门名称,但我不知道如何指定部门并获取属于该部门的员工列表。

任何帮助表示赞赏!

e.g。

var search = new DirectorySearcher(new DirectoryEntry("LDAP://DC=au,DC=company,DC=com"));
search.Filter = "(sAMAccountName=" + userID + ")"; // put the identity name here
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("department");
var res = search.FindOne();

1 个答案:

答案 0 :(得分:2)

如果您想使用旧式DirectorySearcher,那么诀窍是绑定到您要为其列出用户的OU,例如:你的部门:

var searchRoot = new DirectoryEntry("LDAP://OU=YourDepartment,DC=au,DC=company,DC=com");
var search = new DirectorySearcher(searchRoot);

然后再做一次

search.FindAll();

并迭代结果。

另一种选择是使用较新的System.DirectoryServices.AccountManagement命名空间并使用强类型,易于使用的类,例如PrincipalSearcher和“按示例查询”主体做你的搜索:

// create your domain context and define a "starting" container where to search in
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=YourDepartment,DC=au,DC=company,DC=com"))
{
   // define a "query-by-example" principal - here, we search for a UserPrincipal 
   // and with the first name (GivenName) of "Bruce" and a last name (Surname) of "Miller"
   UserPrincipal qbeUser = new UserPrincipal(ctx);
   qbeUser.GivenName = "Bruce";
   qbeUser.Surname = "Miller";

   // create your principal searcher passing in the QBE principal    
   PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

   // find all matches
   foreach(var found in srch.FindAll())
   {
       // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
   }
}

如果您还没有 - 绝对阅读MSDN文章Managing Directory Security Principals in the .NET Framework 3.5,该文章很好地展示了如何充分利用System.DirectoryServices.AccountManagement中的新功能。或者查看MSDN documentation on the System.DirectoryServices.AccountManagement命名空间。

当然,根据您的需要,您可能希望在您创建的“按示例查询”用户主体上指定其他属性:

  • DisplayName(通常:名字+空格+姓氏)
  • SAM Account Name - 您的Windows / AD帐户名称
  • User Principal Name - 您的“username@yourcompany.com”样式名称

您可以在UserPrincipal上指定任何属性,并将其用作PrincipalSearcher的“按示例查询”。

更新:要获取群组成员,请使用以下代码:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find the group in question
    GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

    // if found....
    if (group != null)
    {
       // iterate over members
       foreach (Principal p in group.GetMembers())
       {
           Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
           // do whatever you need to do to those members
       }
    }
}