use*_*795 8 c# ldap active-directory
这是我用来连接LDAP的代码
using (DirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", this.Host, ServerName)))
{
DirEntry.RefreshCache();
if (!string.IsNullOrEmpty(UserName))
{
DirEntry.Username = UserName;
DirEntry.Password = PassWord;
}
if (DirEntry.Properties.Contains("objectGUID"))
{
byte[] guiddatet = (byte[])DirEntry.Properties["objectGUID"].Value;
return new Guid(guiddatet);
}
Run Code Online (Sandbox Code Playgroud)
运行代码时出现"服务器无法运行"错误消息.
有人可以告诉我,我做错了.无论如何要用直接LDAP查询替换上面的代码.
您应该尝试将其分成单独的部分,以便更容易管理逻辑,并且更容易找到发生错误的位置。在这种情况下,我通常采用以下方法:
LdapConnection对象,以便您可以设置所需的选项NetworkCredential使用管理用户名和密码设置实例SearchResultEntry以便您可以处理属性您有几个选项可以帮助您完成此任务,但我会尝试这样的操作:
//Delcare your Network Credential with the administrative Username, Password, and your active directory domain
var credentials = new NetworkCredential(userName, password, domain);
//Create a directory identifier and connection,
var ldapidentifier = new LdapDirectoryIdentifier(serverName, port, false, false);
var ldapconn = new LdapConnection(ldapidentifier, credentials);
Run Code Online (Sandbox Code Playgroud)
接下来,确保您AuthType为您的特定实例设置了正确的设置。由于您是通过端口 389 进行连接,因此只需使用AuthType.Basic.
ldapconn.AuthType = AuthType.Basic;
Run Code Online (Sandbox Code Playgroud)
正如您所询问的,有一种非常简单的方法可以使用此方法设置直接 LDAP 查询。我假设您正在搜索sAMAccountName,但您可以根据需要修改它:
string ldapFilter = "(&(objectCategory=person)(objectClass=user)(&(sAMAccountName={{UserYouAreTryingToFind}})))";
Run Code Online (Sandbox Code Playgroud)
现在我们只需设置搜索请求,并相应地发送它:
//Send the search request with our delimited attribute list
var getUserRequest = new SearchRequest(domain, ldapFilter, SearchScope.Subtree, AttributeList)
{SizeLimit = 1};
//Suppress any refferal creation from happening during the search
var SearchControl = new SearchOptionsControl(SearchOption.DomainScope);
getUserRequest.Controls.Add(SearchControl);
var userResponse = (SearchResponse)ldapconn.SendRequest(getUserRequest);
//This is where I load up the entry I've located,
SearchResultEntry ResultEntry = userResponse.Entries[0];
Run Code Online (Sandbox Code Playgroud)
这应该返回您查询的用户以及您放入AttributeList. 在这种情况下,AttributeList只是一个string[]属性名称的字符串数组 ( ) - 在您的情况下,您需要添加一个名为“objectGUID”的数组。
至于读取 上的属性SearchResultEntry,您可以完全按照原来的操作进行操作:
if(ResultEntry.Attributes.Contains("objectGUID"))
{
// do some stuff here
}
Run Code Online (Sandbox Code Playgroud)
这应该可以帮助您朝着正确的方向前进。
另外,如果您还没有Wireshark的副本,我强烈建议您下载它 - 它对于诊断 Active Directory 的连接问题非常有用。
| 归档时间: |
|
| 查看次数: |
20853 次 |
| 最近记录: |