使用 DistinguishedName 查询 Active Directory

Query Active Directory using DistinguishedName

我有一个使用 Windows 身份验证的应用程序,我正在尝试使用他们的域 ID 获取登录用户信息。

返回的部分数据是用户经理的 DN(在 manager 属性 中)。我需要再次查询 AD 以获取经理的信息(域 ID、电子邮件、姓名等)。 我进行了搜索,但找不到关于我必须在过滤器中使用的内容的任何提示。

这就是我正在使用的,我总是返回 null:

private static DirectoryEntry GetUserDEByDN(string sDN)
{
    using (HostingEnvironment.Impersonate())
    {
        PrincipalContext pc = new PrincipalContext(ContextType.Domain, adUSADomain, adUSAContainer);
        //UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, UserID);
        UserPrincipal qbeUser = new UserPrincipal(pc);
        //qbeUser.SamAccountName = UserID.Trim().ToUpper();

        PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
        PrincipalSearchResult<Principal> psr = srch.FindAll();

        string sDomain = ConfigurationManager.AppSettings["Domain"].ToString();
        string adPath = ConfigurationManager.AppSettings["ADPath"].ToString();

        DirectoryEntry de = new DirectoryEntry(adPath);
        DirectorySearcher deSearch = new DirectorySearcher();
        deSearch.SearchRoot = de;
        deSearch.Filter = "(&(objectClass=user)(| (cn = " + sDN + ")(dn = " + sDN + ")))";

        //deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + UserID + "))";
        deSearch.SearchScope = SearchScope.Subtree;
        SearchResult results = deSearch.FindOne();

        if (null != results)
        {
            de = new DirectoryEntry(results.Path);
            return de;
        }
        else
        {
            return null;
        }
    }
}

是否可以通过 DN 搜索 Active Directory?如果是这样,我做错了什么?

这对我有用。但是,我相信它应该与 objectClass=user 一起使用,但我一直返回 null。当我改为distinguishedName = sDN时,它起作用了。

这段代码的重点

DirectoryEntry de = new DirectoryEntry(adPath + "/" + sDN);

是在用户对象处开始目录搜索;不需要额外搜索说哪个 distinguishedName。

private static DirectoryEntry GetUserDEByDN(string sDN)
{
    string adPath = ConfigurationManager.AppSettings["ADPath"].ToString();
    DirectoryEntry de = new DirectoryEntry(adPath + "/" + sDN);
    DirectoryEntry deManager = null;

    using (DirectorySearcher Search = new DirectorySearcher())
    {
        Search.SearchRoot = de;
        Search.Filter = "(&(distinguishedName=" + sDN + "))";
        //Search.Filter = "(objectClass = user)";
        Search.SearchScope = SearchScope.Base;
        SearchResult Result = Search.FindOne();

        if (null != Result)
            deManager = Result.GetDirectoryEntry();
    }
    return deManager;
}