如何获取AD用户的组成员身份 - 包括其他域中的所有组?

时间:2010-02-04 14:37:51

标签: c# .net active-directory ldap

我已尝试过以下LDAP搜索,但它只为我提供了用户所在域的组成员资格。我需要搜索还包括ForeignSecurityPrincipals组的成员身份(另一个AD域中的组)林)。

public static List<string> GetGroups() 
{ 
  List<string> oGroups = new List<string>(); 
  string vLDAPPath = "GC://dc1.dom1.local/dc=dom1,dc=local"; 
  string vFilterUser = string.Format("(&(objectcategory=user)(objectsid={0}))", "S-1-5-21-122767939-1938435020-1261837966-8097"); 

  DirectoryEntry oDirEntry = new DirectoryEntry(); 
  oDirEntry.Path = vLDAPPath; 
  oDirEntry.Username = "dom1\\sysuser"; 
  oDirEntry.Password = "syspwd"; 

  DirectorySearcher oDirSearchUser = new DirectorySearcher(); 
  oDirSearchUser.SearchRoot = oDirEntry; 
  oDirSearchUser.Filter = vFilterUser; 

  SearchResult oSearchResultUser = oDirSearchUser.FindOne(); 
  if (oSearchResultUser != null) 
  { 
    using (DirectoryEntry oResultDirEntryUser = oSearchResultUser.GetDirectoryEntry()) 
    { 
      oResultDirEntryUser.RefreshCache(new string[] { "TokenGroups" }); 
      PropertyValueCollection tg = oResultDirEntryUser.Properties["TokenGroups"]; 
      foreach (byte[] SID in (Array)tg.Value) 
      { 
        string vFilterGroup = string.Format("(&(objectcategory=group)(objectsid={0}))", SIDToString(SID)); 
        DirectorySearcher oDirSearchGroup = new DirectorySearcher(); 
        oDirSearchGroup.SearchRoot = oDirEntry; 
        oDirSearchGroup.Filter = vFilterGroup; 
        SearchResult oSearchResultGroup = oDirSearchGroup.FindOne(); 
        if (oSearchResultGroup != null) 
        { 
          using (DirectoryEntry oResultDirEntryGroup = oSearchResultGroup.GetDirectoryEntry()) 
          { 
            oGroups.Add(oResultDirEntryGroup.Name); 
          } 
        } 
      } 
    } 
  } 
  return oGroups; 
}

1 个答案:

答案 0 :(得分:0)

使用memberOf属性检索AD组:

C#示例:

private void ConfigureEntry()
{
    // configure your ad connection to the directory
    _currentDirEntry = new DirectoryEntry(_activeDirectoryRoot, _activeDirectoryUser, _activeDirectoryPW);

    DirectorySearch searcher = new DirectorySearcher(_currentDirEntry);
    SearchResult result;

    searcher.Filter = "(sAMAccountName=" & _loginName & ")";   // Or whatever criteria you use to get your directoryEntry
    result = searcher.FindOne

    if(result == null) return;
    _attributes = result.Properties;

    _currentDirEntry = null;
}

private StringCollection MemberBelongsToGroups() 
{
    StringCollection returnCollection = new StringCollection();

    foreach(string prop in _attributes("memberOf")) //_attributes is of type System.DirectoryServices.ResultPropertyCollection
    {
        int equalsIndex = prop.IndexOf("=", 1);
        int commaIndex = prop.IndexOf(",", 1);

        if(equalsIndex >= 0) returnCollection.Add(prop.SubString((equalsindex + 1), (commaIndex - equalsIndex) - 1));
    }

    return returnCollection;
}