LDAPConnection通过NT帐户检索用户

本文关键字:检索 用户 通过 NT LDAPConnection | 更新日期: 2023-09-27 18:15:34

我正在使用System.DirectoryServices.Protocols库查询Active Directory。我有一个用例,我需要从服务器检索用户条目,以用户的NT帐户名称开始(即:NETBIOSDomainName'UserSamAccountName)。这是我使用的代码:

LdapConnection connection = new LdapConnection(userDomain);
NTAccount userAccount = new NTAccount(userDomain, username);
sid = userAccount.Translate(typeof(SecurityIdentifier));
SearchRequest searchRequest = new SearchRequest
{
    Scope = SearchScope.Subtree,
    Filter = string.Format("(&(objectClass=user)(objectsid={0}))", sid)
};
SearchOptionsControl searchOptions = new SearchOptionsControl(SearchOption.PhantomRoot);
searchRequest.Controls.Add(searchOptions);
SearchResponse response = (SearchResponse)connection.SendRequest(searchRequest);

我遇到的问题是,我不知道如何在搜索中包含NetBIOSDomainName。如果我只按用户的samAccountName搜索,我有时会在响应中得到多个条目,因为相同的samAccountName存在于多个域中。

有什么方法可以避免我正在使用的这种hack吗?

请注意,我必须使用这个特殊的库

LDAPConnection通过NT帐户检索用户

如果要查询ActiveDirectory,则使用DirectoryServices。添加对System.DirectoryServices.AccountManagement dll的引用,然后您可以使用如下所示的示例。

目录服务将允许您轻松设置您的域作为查找的一部分。下面的示例返回UserPrincipal,它可用于获取用户帐户的所有详细信息。检查msdn上UserPrincipal上的所有可用属性。

using System.DirectoryServices.AccountManagement;
public UserPrincipal FindUser(string username, string domain)
{
    var context = new PrincipalContext(ContextType.Domain, domain);
    var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
    // user will be null if not found
    // Remember to dispose UserPrincipal once done working with it.
    return user;
}

有一个SearchRequest构造函数的过载,你可以使用- msdn链接,你需要设置第一个参数来限制它到那个域

例子
SearchRequest request = new SearchRequest("DC=mydc,DC=com", sFilter, SearchScope.Subtree);