首页 > 解决方案 > C# - 使用 LDAP 检索 Active Directory 的组成员

问题描述

我的 Active Directory 中有一个“我的组”组,我想使用 Active Directory LDAP 从该组中检索用户。

如何修改我的查询以包含组并从中获取成员?

string username = “ldapuser”;
string password = “prime812”;
DirectoryEntry de = new DirectoryEntry(“LDAP://AM-LDAP-SN.ams.com/389/CN=Users,DC=ms,DC=ds,DC=AMS,dc=com”, username,password);
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.SearchScope = SearchScope.Subtree;

forreach(SearchResult sResultSet in deSearch.FindAll())
{
}

标签: c#active-directoryldap

解决方案


我会使用 PrincipalContext 而不是:

private static List<Principal> GetUsersOfGroup(string groupname)
{
    string username = "ldapuser";
    string password = "prime812";

    using(var pc = new PrincipalContext(ContentType.Domain, null, username, password))
    {
        var _users = new List<Principal>();
        var _group = GroupPrincipal.FindByIdentity(pc, groupname);

        foreach(var member in group.GetMembers())
        {
            if(member is UserPrincipal _user)
                _users.Add(_user);
        }

        return _users;
    }
}

推荐阅读