Linux 下带有 dotnet 核心的 LDAP

LDAP with dotnet core under Linux

我正在开发一个基于 .net 核心 (2.2.103) 的应用程序,它必须连接到 LDAP 服务器。在我的开发机器 运行ning Windows 上,我使用了 System.DirectoryServices 命名空间。 但是,应用程序必须 运行 on Linux (Ubuntu) 而我得到了 PlatformNotSupportedException,所以我添加了对 <PackageReference Include="Novell.Directory.Ldap" Version="2.2.1" /> 并使用了它。

不幸的是,这会在处理连接时抛出另一个 PlatformNotSupportedException(但由于线程中止):

Unhandled Exception: System.PlatformNotSupportedException: Thread abort is not supported on this platform.
   at System.Threading.Thread.Abort()
   at Novell.Directory.Ldap.Connection.Dispose(Boolean disposing, String reason, Int32 semaphoreId, InterThreadException notifyUser)
   at Novell.Directory.Ldap.Connection.destroyClone(Boolean apiCall)
   at Novell.Directory.Ldap.LdapConnection.Finalize()

Linux 上是否有可靠的 dotnet 核心 LDAP 实现?

您尝试使用的包最后更新于 2014 年。它既不符合 .NET Core 也不符合 .NET Standard。

您可以尝试 Novell.Directory.Ldap.NETStandard。尽管名称如此,但这并不是 Novell 库。 NuGet 中还有其他 LDAP 库,但这似乎是最受欢迎的并且仍在积极开发中。

异常表明您也忘记处理连接。 Finalize 仅由垃圾收集器调用。

显示如何使用 Novell.Directory.Ldap.NETStandard 验证用户:

public bool ValidateUser(string domainName, string username, string password)
{
   string userDn = $"{username}@{domainName}";
   try
   {
      using (var connection = new LdapConnection {SecureSocketLayer = false})
      {
         connection.Connect(domainName, LdapConnection.DEFAULT_PORT);
         connection.Bind(userDn, password);
         if (connection.Bound)
            return true;
      }
   }
   catch (LdapException ex)
   {
      // Log exception
   }
   return false;
}

连接是在 using 块内创建的,这确保一旦执行离开块的范围

它就会被释放

如果你想使用跨平台解决方案,你可以使用库 https://github.com/flamencist/ldap4net。该库支持集成身份验证,如 Kerberos\gssapi\negotiate

随着 .NET 5 的发布,Microsoft 为库 System.DirectoryServices.Protocols 添加了跨平台支持(windows、linux、macos)。 System.DirectoryServices 建立在低级别 LDAP API 之上。我希望他们将来 System.DirectoryServices 也可以跨平台。

来源:.NET 5 - expanding directoryservices.protocols to linux and macos

我个人还在用Novell.Directory.Ldap.NETStandard,但我并不满意。我希望我能找到一些时间并尽快切换到 system.directoryservices.protocols 甚至更好的 system.directoryservices 库。