我想从 ASP.NET Core 6 应用程序中的 Active Directory 读取数据。我知道如何使用 DirectorySearcher 来实现这一点:
var entry = new DirectoryEntry(GlobalConfig.Configuration.LDAP, Input.Username, Input.Password);
try
{
var _object = entry.NativeObject;
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = $"(SAMAccountName={Input.Username})";
searcher.PropertiesToLoad.Add("cn");
searcher.PropertiesToLoad.Add("memberOf");
searcher.PropertiesToLoad.Add("employeeid");
searcher.PropertiesToLoad.Add("telephonenumber");
searcher.PropertiesToLoad.Add("displayName");
searcher.PropertiesToLoad.Add("mail");
SearchResult result = searcher.FindOne();
catch(Excepetion ex)
{
// ...
}
但是,此解决方案仅当我们在 Windows 环境中托管应用程序时才有效。有没有办法通过跨平台方法检查这些数据?
最佳答案
您可以使用System.DirectoryServices.Protocols
包,特别是 LdapConnection
类。
示例:
using System.DirectoryServices.Protocols;
...
try
{
using var connection = new LdapConnection("{server}");
var networkCredential = new NetworkCredential(Input.Username, Input.Password, "{domain}");
connection.SessionOptions.SecureSocketLayer = false;
connection.AuthType = AuthType.Negotiate;
connection.Bind(networkCredential);
var searchRequest = new SearchRequest(
"{distinguishedName}",
$"(SAMAccountName={Input.Username})",
SearchScope.OneLevel,
new string[]
{
"cn",
"memberOf",
"employeeid",
"telephonenumber",
"displayName",
"mail"
});
SearchResponse directoryResponse = (SearchResponse)connection.SendRequest(searchRequest);
SearchResultEntry searchResultEntry = directoryResponse.Entries[0];
// ...
}
catch (LdapException ex)
{
// ...
}
相应地修改连接和搜索选项。您可以找到文档here 。您可能会收到有关 LdapSessionOptions.SecureSocketLayer
的警告,表明它仅在 Windows 上受支持,但这是一个错误警告,您可以ignore .
关于c# - 在 ASP.NET Core 6 中检查事件目录的跨平台方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74066273/