如果我有一个用户名,我该如何编写LDAP查询来返回用户所属的所有组?
如果我有一个用户名,我该如何编写LDAP查询来返回用户所属的所有组?
您是否正在使用.NET 3.5?
如果是的话,请查看这篇优秀的MSDN文章《在.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);
}
很容易,是吧?
在.NET 3.5之前或从其他语言(如PHP、Delphi等)使用“直接”LDAP时,需要更多的工作。
Marc
这里有另一种获取组信息的方法:
确保您添加了 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;
}
}