代码之家  ›  专栏  ›  技术社区  ›  Jagd Dai

通过GroupPrincipal查找用户

  •  1
  • Jagd Dai  · 技术社区  · 14 年前

    在我的活动目录(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 
          }
        }
      }
    }
    

    提前感谢你对我的帮助。

    1 回复  |  直到 14 年前
        1
  •  3
  •   John Raymund    13 年前

    通过使用 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;
    }
    

    或者完整的广告参考 here .