C# 在 Linux 上面使用 Windows AD 驗證

在上一篇 C# Windows AD 驗證示範 文章中使用官方的 System.DirectoryServices.AccountManagement 套件來實作 AD 登入,不過只能夠在 Windows 上面使用,如果在 Linux 上執行則會拋出下面的例外:
    
Unhandled exception. System.PlatformNotSupportedException: System.DirectoryServices.AccountManagement is not supported on this platform.
   at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String userName, String password)
   at Program.<Main>$(String[] args) in /mnt/d/ConsoleAppAdTest/ConsoleAppAdTest/Program.cs:line 37
    

目前官方沒有支援跨平台,想要在 Linux 就只能借助第三方套件了,本次使用的是 Github 上的 dsbenghe / Novell.Directory.Ldap.NETStandard 這個套件

先使用 NuGet 安裝 Novell.Directory.Ldap.NETStandard 套件,或是使用 .NET CLI 執行以下指令安裝
	
dotnet add package Novell.Directory.Ldap.NETStandard
    

程式碼:
    
using Novell.Directory.Ldap;
    
string domain = "192.168.0.213";
string username = "ruyut";
string password = "ruyutPassword";
var dc = "dc=ruyut,dc=com"; // ruyut.com

try
{
    using (var connection = new LdapConnection())
    {
        connection.Connect(domain, LdapConnection.DefaultPort);
        connection.Bind($"CN={username},CN=Users,{dc}", password);
        bool connectionBound = connection.Bound;
        Console.WriteLine(connectionBound ? "登入成功" : "登入失敗");
    }
}
catch (LdapException e)
{
    throw;
}

    

留言