我必须在 C# 中检查特定用户的 LDAP Active Directory 用户组。意味着我将此用户名传递给一个方法,它会返回该用户所属的组列表。你能帮我吗?我搜索了很多但每次都得到新的错误。
LDAP 路径:192.168.1.4
域名:阿尔斯兰
用户名:ArslanP
密码:testad
我必须在 C# 中检查特定用户的 LDAP Active Directory 用户组。意味着我将此用户名传递给一个方法,它会返回该用户所属的组列表。你能帮我吗?我搜索了很多但每次都得到新的错误。
LDAP 路径:192.168.1.4
域名:阿尔斯兰
用户名:ArslanP
密码:testad
由于您使用的是 .NET 3.5 及更高版本,因此您应该查看System.DirectoryServices.AccountManagement
(S.DS.AM) 命名空间。在这里阅读所有相关信息:
在 .NET Framework 3.5 中管理目录安全主体
基本上,添加对程序集的引用System.DirectoryServices.AccountManagement
,然后您可以定义域上下文并轻松找到 AD 中的用户和/或组:
using System.DirectoryServices.AccountManagement;
public List<GroupPrincipal> GetGroupsForUser(string username)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();
// set up domain context - if you do a lot of requests, you might
// want to create that outside the method and pass it in as a parameter
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find user by name
UserPrincipal user = UserPrincipal.FindByIdentity(username);
// get the user's groups
if(user != null)
{
foreach(GroupPrincipal gp in user.GetAuthorizationGroups())
{
result.Add(gp);
}
}
return result;
}
新的 S.DS.AM 使得在 AD 中与用户和组一起玩变得非常容易:
这个相关的问题可能会对您有所帮助:
从给定 AD 组中的 Active Directory 获取用户列表
它提出了相反的问题,即当您知道该组时如何 qet 用户列表,但其他答案也可能对您有用。
另请参阅此问题的答案: