获取用户所属的所有 Active Directory 组
get all Active Directory groups a user is member in
我正在寻找一种简单的方法来获取给定用户所属的所有 Active Directory 组。UserPrincipal
中有两种方法,但两者都不符合此要求:
- GetGroups(): returns 所有组,但不是递归的:
This method returns only the groups of which the principal is directly a member; no recursive searches are performed.
- GetAuthorizationGroups():递归工作,但 returns 仅安全组(无分发组)
This function only returns groups that are security groups; distribution groups are not returned.
很遗憾,我无法找到 GetAllGroups()
或 GetDistributionGroups()
之类的内容。是否有递归获取安全和分发组的简短解决方案?
最后我自己写了这个方法,它非常短。
最有帮助的是 Principal
本身包含 .GetGroups()
-Method,因此很容易编写 returns 给定 User-oder GroupPrincipal 的所有组的递归方法。
代码:
private static HashSet<GroupPrincipal> GetAllGroups(Principal principal)
{
Dictionary<string, GroupPrincipal> groups = new Dictionary<string, GroupPrincipal>();
foreach (GroupPrincipal group in principal.GetGroups())
{
groups[group.Sid.ToString()] = group;
foreach (GroupPrincipal childGroup in GetAllGroups(group))
{
groups[childGroup.Sid.ToString()] = childGroup;
}
}
return new HashSet<GroupPrincipal>(groups.Values);
}
我正在寻找一种简单的方法来获取给定用户所属的所有 Active Directory 组。UserPrincipal
中有两种方法,但两者都不符合此要求:
- GetGroups(): returns 所有组,但不是递归的:
This method returns only the groups of which the principal is directly a member; no recursive searches are performed.
- GetAuthorizationGroups():递归工作,但 returns 仅安全组(无分发组)
This function only returns groups that are security groups; distribution groups are not returned.
很遗憾,我无法找到 GetAllGroups()
或 GetDistributionGroups()
之类的内容。是否有递归获取安全和分发组的简短解决方案?
最后我自己写了这个方法,它非常短。
最有帮助的是 Principal
本身包含 .GetGroups()
-Method,因此很容易编写 returns 给定 User-oder GroupPrincipal 的所有组的递归方法。
代码:
private static HashSet<GroupPrincipal> GetAllGroups(Principal principal)
{
Dictionary<string, GroupPrincipal> groups = new Dictionary<string, GroupPrincipal>();
foreach (GroupPrincipal group in principal.GetGroups())
{
groups[group.Sid.ToString()] = group;
foreach (GroupPrincipal childGroup in GetAllGroups(group))
{
groups[childGroup.Sid.ToString()] = childGroup;
}
}
return new HashSet<GroupPrincipal>(groups.Values);
}