c# - 在特定 OU Active Directory 中搜索用户

标签 c# active-directory ou

我的 Active Directory 中针对不同的用户有不同的 OU,我想使用 C# 获取特定 OU 的所有用户。

目前我有这个过滤器,但它会返回所有 OU 的所有用户

(&(objectClass=User)(objectCategory=Person))

请帮助我使用 ldap 查找特定用户的用户

最佳答案

您可以使用 PrincipalSearcher 和“query-by-example”主体进行搜索:

// LDAP string to define your OU
string ou = "OU=Sales,DC=YourCompany,DC=com";

// set up a "PrincipalContext" for that OU
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "Yourcompany.com", ou))
{
    // define the "query-by-example" user (or group, or computer) for your search
    UserPrincipal qbeUser = new UserPrincipal(ctx);

    // set whatever attributes you want to limit your search for, e.g. Name, etc.
    qbeUser.Surname = "Smith";

    // define a searcher for that context and that query-by-example 
    using (PrincipalSearcher searcher = new PrincipalSearcher(qbeUser))
    {
        foreach (Principal p in searcher.FindAll())
        {
            // Convert the "generic" Principal to a UserPrincipal
            UserPrincipal user = p as UserPrincipal;

            if (user != null)
            {
                // do something with your found user....
            }
        }
    }

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

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

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

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

关于c# - 在特定 OU Active Directory 中搜索用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27817738/

相关文章:

c# - 从pdf中提取文本到c#

c# - Arduino 安全地使用 .net Core api?

c# 通过 LDAP 针对 Active Directory

C++。只有在 AD 中授权的用户才能启动该程序

c# - 获取 OU 的完全限定名称

c# - 具体按键错误

c# - 如何从使用存储过程的数据表填充 ListView

azure - ClaimsPrincipal 的哪个属性可用于唯一标识 MVC Controller 中的用户

java - 如何使用java从 Activity 目录中的特定ou获取所有用户?

active-directory - LDAP根查询语法可搜索多个特定的OU