【发布时间】:2009-09-04 18:04:10
【问题描述】:
给定一个用户名,我将如何编写一个 LDAP 查询来返回该用户所属的所有组?
【问题讨论】:
标签: active-directory ldap active-directory-group
给定一个用户名,我将如何编写一个 LDAP 查询来返回该用户所属的所有组?
【问题讨论】:
标签: active-directory ldap active-directory-group
您使用的是 .NET 3.5 吗??
如果是这样,请查看这篇出色的 MSDN 文章 Managing Directory Security Principals in the .NET Framework 3.5,它展示了 .NET 3.5 中用户和组管理的新功能。
在这种情况下,您需要一个主体上下文(例如您的域):
PrincipalContext domainContext =
new PrincipalContext(ContextType.Domain, "YourDomain");
然后你可以很容易地找到用户:
UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, "username");
“UserPrincipal”对象有一个名为“GetAuthorizationGroups”的方法,它返回用户所属的所有组:
PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups();
// display the names of the groups to which the
// user belongs
foreach (Principal result in results)
{
Console.WriteLine("name: {0}", result.Name);
}
很简单吧?
在 3.5 之前的 .NET 中,或者在来自其他语言(PHP、Delphi 等)的“直接”LDAP 中的工作要多得多。
马克
【讨论】:
这是获取组信息的另一种方式:
确保为 System.DirectoryServices 添加引用。
DirectoryEntry root = new DirectoryEntry("LDAP://OU=YourOrganizationOU,DC=foo,DC=bar");
DirectoryEntry user = GetObjectBySAM("SomeUserName", root);
if (user != null)
{
foreach (string g in GetMemberOf(user))
{
Console.WriteLine(g);
}
}
以下方法获取用户条目并返回一个字符串列表,该列表是用户所属的组。
public List<string> GetMemberOf(DirectoryEntry de)
{
List<string> memberof = new List<string>();
foreach (object oMember in de.Properties["memberOf"])
{
memberof.Add(oMember.ToString());
}
return memberof;
}
public DirectoryEntry GetObjectBySAM(string sam, DirectoryEntry root)
{
using (DirectorySearcher searcher = new DirectorySearcher(root, string.Format("(sAMAccountName={0})", sam)))
{
SearchResult sr = searcher.FindOne();
if (!(sr == null)) return sr.GetDirectoryEntry();
else
return null;
}
}
【讨论】: