简体   繁体   English

C#从Active Directory获取特定用户的所有组

[英]C# Get all groups of specific user from Active Directory

I'm trying to get all the groups of a specific user, as it listed in Active Directory "Member Of" groups. 我正在尝试获取特定用户的所有组,如Active Directory“成员”组中列出的那样。 I found a code but it gives me all of the groups, if a group contains few groups, I get those groups instead of the main one that contains them.. I would like to get the list as it is without "background" groups. 我找到了一个代码,但是它给了我所有的组,如果一个组包含几个组,我将得到那些组,而不是包含它们的主要组。

code that i found here: 我在这里找到的代码:

public List<GroupPrincipal> GetGroups(string userName)
{
   List<GroupPrincipal> result = new List<GroupPrincipal>();

   // establish domain context
   PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);

   // find your user
   UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);

   // if found - grab its groups
   if(user != null)
   {
      PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();

      // iterate over all groups
      foreach(Principal p in groups)
      {
         // make sure to add only group principals
         if(p is GroupPrincipal)
         {
             result.Add((GroupPrincipal)p);
         }
      }
   }

   return result;
}

Haven't find a working solution yet, any idea? 还没有找到可行的解决方案,知道吗?

The GetAuthorizationGroups() method is for testing the user's security privileges. GetAuthorizationGroups()方法用于测试用户的安全特权。 It tells you that the user is entitled to all the security privileges that the returned groups are given. 它告诉您用户有权获得返回组的所有安全特权。 So it does give you all the nested security groups. 因此,它确实为您提供了所有嵌套的安全组。

For example, if the user is a member of group B, and group B is in group A, then the user is entitled to the privileges granted to group A, therefore GetAuthorizationGroups() will return group A. 例如,如果用户是组B的成员,并且组B在组A中,则该用户有权获得授予组A的特权,因此GetAuthorizationGroups()将返回组A。

I think what you're looking for is the GetGroups() method, which returns only the groups the user is an immediate member of. 我认为您正在寻找的是GetGroups()方法,该方法仅返回用户是其直接成员的组。

PrincipalSearchResult<Principal> groups = user.GetGroups();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM