在我的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
}
}
}
}
提前感谢我收到的任何帮助。
答案 0 :(得分:3)
使用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。