【问题标题】:Get List of all users of specific ActiveDirectoryGroup获取特定 ActiveDirectoryGroup 的所有用户的列表
【发布时间】:2019-03-21 03:17:13
【问题描述】:

您好,我尝试获取 ActiveDirectory 组的所有用户的列表。 Windows 身份验证已正确设置并按预期工作。我还可以将特定的控制器操作限制为特定的 AD 组/角色。

但是,我无法获得特定 AD 组的所有用户的简单列表。

我在我的控制器中尝试了以下操作:

[HttpGet]
public async Task<IActionResult> Test()
{    
    string username = HttpContext.User.Identity...; //nothing to find in here

    return View();
}

我使用一些私有 UserManager 变量或上下文变量找到了其他答案,但是我的控制器中没有它们,并且我找到的其他答案,不要告诉我如何获取它们...

任何帮助将不胜感激。

【问题讨论】:

  • 没有内置方式。将 Windows Auth 视为本质上的外部登录提供程序,如 Google 或 Facebook。如果您想同时使用其中任何一个用户获取一组用户的信息,则必须求助于使用他们的 API。同样,使用 Windows 身份验证,您必须创建与 AD 服务器的 LDAP 连接并直接从那里查询信息。
  • 感谢您的快速回复!我不明白为什么没有内置此功能,而其他所有功能都非常好...但是:对于您描述的方式,有什么好的教程吗?
  • 为什么要内置?它与身份验证无关,这是 Windows Auth 的全部内容。对于一般信息查询,AD是真相的来源,所以这就是你需要咨询的。就教程而言,只需进行搜索即可。这里没有特定于 ASP.NET Core 的内容。它只是 LDAP,就像您在任何地方所做的一样。
  • @ChrisPratt 非常感谢您的评论。我现在确实明白为什么它没有内置,并且我只需在互联网上进行很少的研究就能够找到一个易于实施的解决方案!

标签: c# active-directory asp.net-core-2.0 windows-authentication user-roles


【解决方案1】:

正如@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;
            }
        }
    }
}

现在从我的控制器中我只需执行以下操作:

[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);
}

我希望这篇文章将来可能对其他人有所帮助,这就是我将其发布为答案的原因。

【讨论】:

    【解决方案2】:

    不太确定是否可以选择使用 powershell 来获取 AD 中组的列出用户--- Get-ADGroup "group name" |获取-ADGroupMember |选择对象 samaccountname

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 2016-03-04
      相关资源
      最近更新 更多