views:

78

answers:

1

I have tried the below LDAP search, but it only gives me the group membership for the domain the user is in. I need it to include also the memberships of the foreign security principals.

public static List GetGroups() { List oGroups = new List(); 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; }

A: 

AD groups are retrieved by using the memberOf attribute:

C# Example:

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;
}
Joel Etherton