您好,我尝试获取 ActiveDirectory 组的所有用户的列表。 Windows 身份验证已正确设置并按预期工作。我还可以将特定 Controller 操作限制为特定的 AD 组/角色。
但是,我无法获取特定 AD 组的所有用户的简单列表。
我在 Controller 中尝试了以下操作:
[HttpGet]
public async Task<IActionResult> Test()
{
string username = HttpContext.User.Identity...; //nothing to find in here
return View();
}
我使用一些私有(private) UserManager 变量或上下文变量找到了其他答案,但是我的 Controller 中没有它们,并且我找到的其他答案没有告诉我如何获取它们...
任何帮助将不胜感激。
最佳答案
正如 @Chris Pratt 在他的评论中提到的,没有任何构建方法可以使用 ASP.NET Core 2.0 解决此问题,但有一个简单的方法,即使用 C# 来解决。
所以我所做的非常简单,首先我创建了以下类(深受启发: https://stackoverflow.com/a/19604001/9641435 )
using System.DirectoryServices.AccountManagement; //can be downloaded via NUGET Package manager
using System.Collections.Generic;
namespace MYNAMESPACE
{
public static class ActiveDirectoryHelper
{
public static List<string> GetAllUserRealNamesFromAdGroup(string i_activeDirectyGroup)
{
var users = new List<string>();
using (var context = new PrincipalContext(ContextType.Domain, "MY.DOMAIN.NAME"))
{
using (var group = GroupPrincipal.FindByIdentity(context, i_activeDirectyGroup))
{
if (group != null)
{
var usersPrincipals = group.GetMembers(true);
foreach (UserPrincipal user in usersPrincipals)
{
//There are also other properties available, but in my case I just need the first and surname:
users.Add($"{user.GivenName} {user.Surname}");
}
}
}
return users;
}
}
}
}
现在从我的 Controller 中我只需执行以下操作:
[HttpGet]
public IActionResult MyAction()
{
var myVm = new MyViewModel();
List<string> userList = ActiveDirectoryHelper.GetAllUserRealNamesFromAdGroup("MYGROUP");
//do whatever you want with this list right here:
return View(myVm);
}
我希望这篇文章将来可以对其他人有所帮助,这就是我将其发布为答案的原因。
关于c# - 获取特定 ActiveDirectoryGroup 的所有用户的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52838005/