从Active directory中的特定组和OU中检索用户
本文关键字:OU 检索 用户 Active directory | 更新日期: 2023-09-27 18:03:25
我想从Active Directory中的特定OU检索给定组中的所有用户。我的代码抛出了一个异常
操作被中止,因为超出了客户端超时限制
我在
处得到这个异常foreach (SearchResultEntry entry in searchResponse.Entries)
我的组名是Arya
, OU名是TestOU
但是当我把过滤器写成
string searchFilter = "(&(objectCategory=user)"
它工作并返回所有OU的用户,我认为这是我不想要的。
bool bMoreData = false;
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://" + domain);
string[] attributes = { "samaccountname", "displayname", "name", "initials" };
System.Net.NetworkCredential credential = new System.Net.NetworkCredential(admin, password, "IP address");
LdapDirectoryIdentifier directoryIdentifier = new LdapDirectoryIdentifier("ip address"); //389 (unsecured LDAP)
LdapConnection connection = new LdapConnection(directoryIdentifier, credential);
connection.Bind();
string searchFilter = "(&(objectCategory=user)(memberOf=cn=Arya,ou=TestOU,dc=Maintenance,dc=org))";
SearchRequest request = new SearchRequest("DC=Maintenance,DC=org", searchFilter, System.DirectoryServices.Protocols.SearchScope.Base, attributes);
// getCookie();
DirSyncRequestControl dirSyncRC = new DirSyncRequestControl(cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions.IncrementalValues, Int32.MaxValue);
request.Controls.Add(dirSyncRC);
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(request);
foreach (SearchResultEntry entry in searchResponse.Entries)// Exception thrown here
{
Console.WriteLine("{0}:{1}",
searchResponse.Entries.IndexOf(entry),
entry.DistinguishedName);
}
foreach (DirectoryControl control in searchResponse.Controls)
{
if (control is DirSyncResponseControl)
{
DirSyncResponseControl dsrc = control as DirSyncResponseControl;
cookie = dsrc.Cookie;
bMoreData = dsrc.MoreData;
break;
}
}
我发现下面一行
有问题DirSyncRequestControl dirSyncRC = new DirSyncRequestControl(cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions.IncrementalValues, Int32.MaxValue);
当它被替换成它为我工作。
DirSyncRequestControl dirSyncRC = new DirSyncRequestControl(cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions.ObjectSecurity, Int32.MaxValue);
您可以为您的OU绑定PrincipalContext
,然后找到您正在寻找的组:
// create your domain context - bind to the OU you're interested in
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, "OU=TestOU"))
{
// define a "query-by-example" principal - here, we search for any GroupPrincipal
GroupPrincipal group = ctx.FindByIdentity("Arya");
// if group is found - enumerate its members
if(group != null)
{
foreach(var found in group.GetMembers())
{
//
}
}
}
如果你还没有-绝对阅读MSDN文章管理。net框架3.5中的目录安全原则(可从微软下载的.CHM
文件- 2008年1月的MSDN杂志),它很好地展示了如何充分利用System.DirectoryServices.AccountManagement
中的新特性。或者查看System.DirectoryServices.AccountManagement命名空间上的MSDN文档。