ASP.NET Core 6中检查active directory的跨平台方式



我想从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)
{
// ...
}

相应地修改连接和搜索选项。您可以在这里找到文档。您可能会收到LdapSessionOptions.SecureSocketLayer的警告,即它仅在Windows上受支持,但这是一个可以忽略的错误警告。

最新更新