首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过GroupPrincipal查找用户

通过GroupPrincipal查找用户
EN

Stack Overflow用户
提问于 2010-11-16 22:23:06
回答 1查看 4.6K关注 0票数 2

在我的Active Directory (my.domain)中,我有许多组(UserGrp1、UserGrp2等)。有很多用户。一个用户可以存在于多个组中。我目前有一些代码,允许我使用GroupPrincipal类查找一个组,然后从那里获取该组的所有成员(参见下面的代码)。然而,我真正需要的是找到用户所属的所有组,例如,我有一个名为Joe ()的域用户,我需要找到他所属的所有组。做这件事最好的方法是什么?

如果我循环遍历GetMembers()方法返回的所有成员,我可以确定用户是否属于一个组(如下所示),但这对我来说似乎效率低下,如果没有更有效的方法,我会感到惊讶。

代码语言:javascript
复制
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 
      }
    }
  }
}

谢谢你在这方面给我的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-11-18 03:46:38

通过使用UserPrincipal.GetGroups();来实现

要获得完整的代码,这里是

代码语言:javascript
复制
/// <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;
}

或者,对于一个完整的广告参考,去这里

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4199667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档