c# - 在 ASP.NET Core 6 中检查事件目录的跨平台方法

标签 c# asp.net asp.net-core active-directory ldap

我想从 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/

相关文章:

c# - 转向资源重构

c# - 在 C# 中运行存储过程,传递参数并捕获输出结果

javascript - 使用 Url.action() 传递动态 javascript 值

c# - 使用命名元组作为输入参数的 API 调用

c# - 从操作返回文件时,流是否会被处置?

c# - 哈希表中的列表丢失所有条目

c# - 多次指定固定名称 System.Data.SqlClient 的提供程序

C# DateTime.ParseExact 确定年份前缀

asp.net - RequireNonLetterOrDigit 未正确验证

c# - 记录未插入 Access 数据库