c# - 获取特定 ActiveDirectoryGroup 的所有用户的列表

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

您好,我尝试获取 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/

相关文章:

.net - 使用 Active Directory 进行 .NET 中的用户组和角色管理

asp.net-core-2.0 - 如何在 ASP.NET Core 2.0 中为 EFCore 2 配置 SQL 日志记录

c# - 谁以及如何在依赖注入(inject)中初始化接口(interface)

c# - 重写 IL 以在方法调用周围注入(inject) try-finally

C# InvalidArgument= '1' 的值对于 'index' 无效

database - IIS 如何从 LDAP 请求信息?

node.js - Passport-ldapauth 获取嵌套组

c# - 在 ASP.Net MVC Core 2.0 中设置登录 url

c# - 备用应用程序。在 Program.cs 文件中运行 Winform

c# - 自动映射器的通用扩展方法