c# - Active Directory 在 C# 中找不到所有用户

标签 c# active-directory directoryservices

我有一些代码可以查询 Active Directory 以验证用户是否存在。我正在尝试验证一长串大约 1300 个 ID。我已经尝试了几种方法来验证用户帐户(LINQ to AD、DirectorySearcher(有和没有父 DirectoryEntry)以及链接到 WinNT://路径的 DirectoryEntry)。每次都会回来说几个用户不存在。如果我在代码中硬编码他们的用户 ID 并单独执行,它会验证存在。如果我尝试在 foreach 循环中执行此操作,我会得到几个漏报。

这是我现在正在使用的代码..

static string[] userIDs = new string[] "user1","user2","user3","user4","user5","user6","user7","user8"...,"user1300"};

List<string> nonExistingUsers = new List<string>();
List<string> ExistingUsers = new List<string>();
foreach (string s in userIDs)
{
 DirectorySearcher search = new DirectorySearcher();
 search.Filter = String.Format("(SAMAccountName={0})", s);
 search.PropertiesToLoad.Add("cn");
 DirectorySearcher ds = new DirectorySearcher(de, "(&(objectClass=user)(cn=" + s + "))", new string[] { "Name" }, SearchScope.Subtree);
 SearchResultCollection resultCollection = ds.FindAll();
 SearchResult result = search.FindOne();
 if (result != null)
  ExistingUsers.Add(s);
 else
  nonExistingUsers.Add(s);
}

我得到假阴性的任何建议或原因?

最佳答案

一些事情:

  • 首先,尝试在您的 LDAP 过滤器中使用“anr=”(歧义名称解析)- 它会搜索几个与名称相关的属性并使搜索更容易。 UserID 可能不是实际“通用名称”(CN=user1) 的一部分

  • 其次,使用 objectCategory 而不是 objectClass - objectCategory 是单值和索引的,因此搜索速度要快一些

  • 第三:您为什么先调用 .FindAll() 然后在下一行调用 .FindOne()?似乎根本没有必要....

  • WinNT://确实只是为了向后兼容,如果您需要处理本地计算机帐户 - 尽可能避免使用它,它公开的属性也比 LDAP 少得多

这是我要编写的代码:

static string[] userIDs = new string[] "user1","user2","user3","user4","user5","user6","user7","user8"...,"user1300"};

DirectoryEntry searchRoot = new DirectoryEntry("LDAP://cn=Users,dc=YourComp,dc=com");

List<string> nonExistingUsers = new List<string>();
List<string> ExistingUsers = new List<string>();

foreach (string s in userIDs)
{
   DirectorySearcher search = new DirectorySearcher(searchRoot);

   search.SearchScope = SearchScope.Subtree;
   search.Filter = string.Format("(&(objectCategory=person)(anr={0}))", s);

   SearchResultCollection resultCollection = ds.FindAll();

   if(resultCollection != null && resultCollection.Count > 0)
      ExistingUsers.Add(s);
   else
      nonExistingUsers.Add(s);
}

这在您的场景中行得通吗?

此外,如果您使用的是 .NET 3.5 或更高版本,事情会变得容易得多 - 请参阅:

Managing Directory Security Principals in the .NET Framework 3.5

关于c# - Active Directory 在 C# 中找不到所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1829093/

相关文章:

c# - 在使用 LDAP 验证之前散列密码

c# - 根据 AD 组成员身份限制对 WPF View 的访问

c# - 使用 System.DirectoryServices.AccountManagement 我收到奇怪的错误

azure - 在不使用注册策略的情况下将用户添加到 Azure B2C

active-directory - DirectoryServices.AccountManagement "old"密码更改后仍然有效

c# - 如果结构包含 DateTime 字段,为什么 LayoutKind.Sequential 的工作方式不同?

c# - AutoEllipsis=true 影响文本的垂直定位

powershell - 您可以在 Get-ADUser 上使用 -Filter 来过滤掉空字段吗?

c# - 如何以编程方式更改 Active Directory 密码

c# - 无法提取信息