如何使用System.DirectoryServices.AccountManagement在多个领

2019-07-29 06:17发布

我有三个或多个域像main.comsub.main.comsub2.main.com和等

我有一个代码:

using (PrincipalContext ctx = 
    new PrincipalContext(ContextType.Domain, "ADServer", 
    "dc=main,dc=com", ContextOptions.Negotiate))
{
    UserPrincipal u = new UserPrincipal(ctx);
    u.UserPrincipalName = "*" + mask + "*";

    using (PrincipalSearcher ps = new PrincipalSearcher(u))
    {
       PrincipalSearchResult<Principal> results = ps.FindAll();
       List<ADUser> lst = new List<ADUser>();

       foreach (var item in results.Cast<UserPrincipal>().Take(15))
       {
           byte[] sid = new byte[item.Sid.BinaryLength];
           item.Sid.GetBinaryForm(sid, 0);

           ADUser us = new ADUser()
           {
               Sid = sid,
               Account = item.SamAccountName,
               FullName = item.DisplayName
           };

           lst.Add(us);
       }

    }

    return lst;
}

但它只搜索一个领域内: main.com

我怎样才能在同一时间搜索记录在所有领域?

Answer 1:

这里有一个方法来找到根一个你的所有域:

/* Retreiving RootDSE
 */
string ldapBase = "LDAP://DC_DNS_NAME:389/";
string sFromWhere = ldapBase + "rootDSE";
DirectoryEntry root = new DirectoryEntry(sFromWhere, "AdminLogin", "PWD");
string configurationNamingContext = root.Properties["configurationNamingContext"][0].ToString();

/* Retreiving the root of all the domains
 */
sFromWhere = ldapBase + configurationNamingContext;
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "AdminLogin", "PWD");

DirectorySearcher dsLookForDomain = new DirectorySearcher(deBase);
dsLookForDomain.Filter = "(&(objectClass=crossRef)(nETBIOSName=*))";
dsLookForDomain.SearchScope = SearchScope.Subtree;
dsLookForDomain.PropertiesToLoad.Add("nCName");
dsLookForDomain.PropertiesToLoad.Add("dnsRoot");

SearchResultCollection srcDomains = dsLookForDomain.FindAll();

foreach (SearchResult aSRDomain in srcDomains)
{
}

随后的foreach域,你可以看看你需要什么。



Answer 2:

您应该使用GC,而不是LDAP。 它沿着整个域森林搜索

var path="GC://DC=main,DC=com";
try {
  using (var root = new DirectoryEntry(path, username, password)) {
    var searchFilter=string.Format("(&(anr={0})(objectCategory=user)(objectClass=user))", mask);
    using (var searcher = new DirectorySearcher(root, searchFilter, new[] { "objectSid", "userPrincipalName" })) {
    var results = searcher.FindAll();
    foreach(SearchResult item in results){
       //What ever you do
    }
} catch (DirectoryServicesCOMException) {
    // username or password are wrong
}


Answer 3:

实际使用System.DirectoryServices.AccountManagement做搜索,指定域这样的:

new PrincipalContext(ContextType.Domain, "xyz.mycorp.com:3268", "DC=mycorp,DC=com");

从什么时候我需要一个域名和一个域容器创建PrincipalContext?



文章来源: How to search in multiple domains using System.DirectoryServices.AccountManagement?