【问题标题】:Finding a user through the GroupPrincipal通过 GroupPrincipal 查找用户
【发布时间】:2010-11-16 22:23:06
【问题描述】:

在我的 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 
      }
    }
  }
}

在此先感谢我在这方面收到的任何帮助。

【问题讨论】:

    标签: .net active-directory


    【解决方案1】:

    使用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

    【讨论】:

    • 谢谢,雷蒙德!不敢相信我以某种方式错过了 UserPrincipal 中的 GetGroups() 方法。它正盯着我的脸!
    • 大声笑!我猜这不会发生在每个人身上
    猜你喜欢
    • 2018-09-25
    • 1970-01-01
    • 2015-12-23
    • 2018-01-04
    • 2012-04-07
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多