如何检索组中的用户,包括主要组用户

时间:2011-06-20 17:41:45

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

我正在使用.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;
    }
}

1 个答案:

答案 0 :(得分:4)

用户的主要组由用户的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]);
}