从NetCore 2.0中的active directory获取所有用户



所有问题都与.NET框架有关,但与.NET核心无关。我正在寻找如何在NETCORE中从AD组获得所有用户信息。

我使用的是.Net Core 3.1,但您也可以与.Net Core 2一起使用。

首先安装NuGet包";System.DirectoryServices.AccountManagement";

然后,您可以使用下面的代码来获取所有AD用户:

using System.DirectoryServices.AccountManagement; 

public static List<ADUser> GetADUsers() {
var myDomainUsers = new List<ADUser>();
using (var ctx = new PrincipalContext(ContextType.Domain, "yourdomain"))
{
var userPrinciple = new UserPrincipal(ctx);
using (var search = new PrincipalSearcher(userPrinciple))
{
foreach (UserPrincipal domainUser in search.FindAll().OrderBy(u => u.DisplayName))
{
var adUser = new ADUser() {
Description = domainUser.Description,
DisplayName = domainUser.DisplayName,
DistinguishedName = domainUser.DistinguishedName,
EmailAddress = domainUser.EmailAddress,
Name = domainUser.Name,
EmployeeId = domainUser.EmployeeId,
GivenName = domainUser.GivenName,
MiddleName = domainUser.MiddleName,
Surname = domainUser.Surname,
SamAccountName  = domainUser.SamAccountName
}; 
myDomainUsers.Add(adUser);
} //foreach
} //using
} //using
return myDomainUsers;
} //GetADGroups

我在哪里使用以下ADUser类:

public class ADUser
{
public string SamAccountName { get; set; }
public string Description { get; set; }
public string DisplayName { get; set; }
public string DistinguishedName { get; set; }
public string EmailAddress { get; set; }
public string EmployeeId { get; set; }
public string Name { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
public string Surname { get; set; }
}

你可以从AD中提取更多的属性。看看UserPrincipal类

我正在使用Novell.Directory.Ldap包连接到Ldap以验证我的用户。

项目.csproj

<PackageReference Include="Novell.Directory.Ldap.NETStandard" Version="2.3.8" />

编码.cs

using Novell.Directory.Ldap;
public bool LoginLdap(string username, string password)
{
LdapConnection connection = new LdapConnection();
var loggedIn = false;
try
{
connection.Connect(_config["Ldap:url"], LdapConnection.DEFAULT_PORT);
connection.Bind(LdapConnection.Ldap_V3, _config["Ldap:domain"] + @"" + username, password);
loggedIn = true;
}
catch 
{
loggedIn = false;
}
connection.Disconnect();
return loggedIn;
}

Config.json

"Ldap": {
"url": "[Ldap URL]",
"domain": "[Domain Name]"
}

如果您只计划在Windows中运行应用程序,您可以从NuGet将Microsoft.Windows.Compatibility添加到您的项目中,其中包括System.DirectoryServices命名空间,因此您可以像在完整的.NET Framework中一样使用DirectoryEntry/DirectorySearcherAccountManagement命名空间。

但如果你计划在其他操作系统上运行这个,那么我认为唯一的选择就是Novell的库,正如Steve在回答中提到的那样。

最新更新