Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am receiving an unusual behaviour in my asp.net application. I have code that uses Directory Services to find the AD groups for a given, authenticated user. The code goes something like ...

string username = "user"; 
string domain = "LDAP://DC=domain,DC=com"; 
DirectorySearcher search = new DirectorySearcher(domain); 
search.Filter = "(SAMAccountName=" + username + ")"; 

And then I query and get the list of groups for the given user. The problem is that the code was receiving the list of groups as a list of strings. With our latest release of the software, we are starting to receive the list of groups as a byte[].

The system will return string, suddenly return byte[] and then with a reboot it returns string again.

Anyone have any ideas?

code sample:

DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + ldapSearchBase);  
DirectorySearcher userSearcher = new DirectorySearcher(dirEntry)  
  { SearchScope = SearchScope.Subtree,  
    CacheResults = false,  
    Filter = ("(" + txtLdapSearchNameFilter.Text + "=" + userName + ")") 
  };  

userResult = userSearcher.FindOne();  
ResultPropertyValueCollection valCol = userResult.Properties["memberOf"];  

foreach (object val in valCol)  
{  
    if (val is string)  
    { 
        distName = val.ToString(); 
    }  
    else  
    {  
        distName = enc.GetString((Byte[])val);  
    } 
 }
share|improve this question
add comment

1 Answer

Since the user is authenticated, you have their token. The token has their complete group memberships. No need to query AD for the groups. (You may need to query to translate the SIDs to friendly names though).

If you're able to impersonate, it's could be as easy as this:

using (WindowsImpersonationContext userImpersonationContext = WindowsIdentity.Impersonate(Request.LogonUserIdentity.Token))  
{  
    WindowsIdentity _identity = WindowsIdentity.GetCurrent();

    IdentityReferenceCollection _adGroups = _identity.Groups;
    StringBuilder _adGroupsSb = new StringBuilder();
    foreach (IdentityReference _group in _adGroups)
    {
        _adGroupsSb.AppendLine(_group.Translate(typeof(NTAccount)).Value);
    }

    log.Info("User: " + _identity.Name + "; " + _adGroups.Count + " groups: " +
        Environment.NewLine + Environment.NewLine + _adGroupsSb.ToString());
}

If you're set on querying AD, I would check out using TokenGroups instead of MemberOf. Joe Kaplan's web site has some good examples on this.

http://directoryprogramming.net/files/3/csharp/entry1.aspx

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.