【问题标题】:How to retrieve Users in a Group, including primary group users如何检索组中的用户,包括主要组用户
【发布时间】:2011-06-20 17:41:45
【问题描述】:

我在 .net 2.0 中工作,需要检索给定 AD 组的所有用户。我有以下方法可以返回组的所有成员,但它不会返回将传递组作为主要组的用户。我需要做些什么才能让这些用户也包括在内?

/// <summary>
/// Gets the group child users.
/// </summary>
/// <param name="parentGroup">The parent group.</param>
/// <returns></returns>
public List<ADUser> GetGroupChildUsers(ADGroup parentGroup)
{
    List<ADUser> list = new List<ADUser>();

    DirectoryEntry entry = GetDirectoryEntry(LdapBaseString);

    DirectorySearcher searcher = new DirectorySearcher(entry);
    searcher.Filter = string.Format("(&(objectCategory=person)(memberOf={0}))", parentGroup.DN);

    searcher.PropertiesToLoad.Add("objectGUID");
    searcher.SizeLimit = MaxReturnCount;

    SearchResultCollection results = searcher.FindAll();

    foreach (SearchResult result in results) {
        Guid guid = new Guid((byte[])result.Properties["objectGUID"][0]);
        list.Add(GetUserByGuid(guid));
    }

    if (list.Count <= 0) {
        return null;
    } else {
        return list;
    }
}

【问题讨论】:

标签: .net active-directory .net-2.0


【解决方案1】:

用户的主要组由用户的primaryGroupID 属性给出。事实上,primaryGroupID 以字符串格式包含主要组的 RID。这就是为什么,我首先获取您正在寻找用户的组的 SID,然后我(错误地)计算 RID,并使用包含 RID 的 primaryGroupID 搜索用户。

/* Connection to Active Directory
 */
DirectoryEntry deBase = new DirectoryEntry("LDAP://WM2008R2ENT:389/dc=dom,dc=fr");

/* Directory Search for agroup
 */
string givenGrpName = "MonGrpSec"; 
DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
dsLookFor.Filter = string.Format ("(sAMAccountName={0})", givenGrpName);
dsLookFor.SearchScope = SearchScope.Subtree;
dsLookFor.PropertiesToLoad.Add("cn");
dsLookFor.PropertiesToLoad.Add("objectSid");

SearchResult srcGrp = dsLookFor.FindOne();

/* Get the SID
 */
SecurityIdentifier secId = new SecurityIdentifier(srcGrp.Properties["objectSid"][0] as byte[], 0);

/* Find The RID (sure exists a best method)
 */
Regex regRID = new Regex(@"^S.*-(\d+)$");
Match matchRID =  regRID.Match(secId.Value);
string sRID = matchRID.Groups[1].Value;

/* Directory Search for users that has a particular primary group
 */
DirectorySearcher dsLookForUsers = new DirectorySearcher(deBase);
dsLookForUsers.Filter = string.Format("(primaryGroupID={0})", sRID);
dsLookForUsers.SearchScope = SearchScope.Subtree;
dsLookForUsers.PropertiesToLoad.Add("cn");

SearchResultCollection srcUsers = dsLookForUsers.FindAll();

foreach (SearchResult user in srcUsers)
{
  Console.WriteLine("{0} is the primary group of {1}", givenGrpName, user.Properties["cn"][0]);
}

【讨论】:

  • 令人印象深刻。你知道如何获取嵌套安全和通讯组类型的所有成员吗?
  • 是的,您已经在this 其他帖子或here 中得到了答案。 .
  • 根据您提供的解决方案,据我所知,获取所有组成员的方法是查找用户属于哪些组。我对么?我试图实现的方法是另一种方式:它获取包含在组本身中的所有成员。这样做的原因是组比用户少得多。因此,获取每个用户所在的组将导致同一个组被多次点击。是否可以只检查一个组并获取所有成员而不考虑 groupType?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多