我想從 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 環境中時才有效。有沒有辦法用跨平臺方法檢查這些資料?
uj5u.com熱心網友回復:
您可以使用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 上受支持,但這是您可以忽略的錯誤警告。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/514896.html
標籤:C#网asp.net 核心活动目录
上一篇:如何解決下面出現@role.Name的null錯誤?
下一篇:使用DI的授權需求處理程式
