在我的 Active Directory (my.domain) 中,我有许多组(UserGrp1、UserGrp2 等),其中有许多用户。一个用户可以存在于多个组中。我目前的代码允许我使用 GroupPrincipal 类来查找组,然后从那里获取该组的所有成员(请参阅下面的代码)。然而,我真正需要的是找到用户所属的所有组。例如,我有一个名为 Joe Test (sAMAccountName=JOETEST) 的域用户,我需要查找他所属的所有组。做这个的最好方式是什么?
如果我循环访问 GetMembers() 方法返回的所有成员,我可以确定用户是否属于某个组(如下所示),但这对我来说似乎效率低下,如果没有更有效的方法,我会感到惊讶。
using (PrincipalContext ctx = new PrincipalContext(
ContextType.Domain, "my.domain", "DC=my,DC=domain")) {
if (ctx != null) {
using (GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctx, "UserGrp1")) {
// Get all group members
PrincipalSearchResult<Principal> psr = gp.GetMembers();
foreach (Principal p in psr) {
// other logic
}
}
}
}
预先感谢我在这方面收到的任何帮助。
通过使用来做到这一点UserPrincipal.GetGroups();
对于完整的代码,这里是
/// <summary>
/// Gets a list of the users group memberships
/// </summary>
/// <param name="sUserName">The user you want to get the group memberships</param>
/// <returns>Returns an arraylist of group memberships</returns>
public ArrayList GetUserGroups(string sUserName)
{
ArrayList myItems = new ArrayList();
UserPrincipal oUserPrincipal = GetUser(sUserName);
PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
foreach (Principal oResult in oPrincipalSearchResult)
{
myItems.Add(oResult.Name);
}
return myItems;
}
/// <summary>
/// Gets a certain user on Active Directory
/// </summary>
/// <param name="sUserName">The username to get</param>
/// <returns>Returns the UserPrincipal Object</returns>
public UserPrincipal GetUser(string sUserName)
{
PrincipalContext oPrincipalContext = GetPrincipalContext();
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
return oUserPrincipal;
}
/// <summary>
/// Gets the base principal context
/// </summary>
/// <returns>Retruns the PrincipalContext object</returns>
public PrincipalContext GetPrincipalContext()
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword);
return oPrincipalContext;
}
或者要获取完整的 AD 参考,请访问here http://anyrest.wordpress.com/2010/06/28/active-directory-c/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)