Ben

Ben

  • NA
  • 1
  • 0

Get groups a user is a member of in Active Directory

Jun 3 2009 11:20 AM
Hi,
I am trying to write a method to get all the groups that a particular user is a member of off of our LDAP server the code below is my function:
    /// <summary>
/// Gets a list of all the groups the user is currentlya member of
/// </summary>
/// <param name="userName">name of the user</param>
/// <returns>List of all groups the user is currently a member of</returns>
private LinkedList<string> getUsersGroupMemberships(string userName)
{
LinkedList<string> groups = new LinkedList<string>();

string path = cnst.Address + "/" + cnst.BaseDN;
DirectoryEntry dirEntry = new DirectoryEntry("LDAP://"+cnst.BaseDN,cnst.MasterName,cnst.MasterPswd);
DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry,
"(&(objectclass=user)(cn="+userName+"))");

dirSearcher.PropertiesToLoad.AddRange(new string[] { "memberOf" });
dirSearcher.SearchScope = SearchScope.Subtree;
SearchResult rslt = dirSearcher.FindOne();

if (rslt != null)
{
DirectoryEntry usrEntry = new DirectoryEntry(rslt.Path);
object objs = usrEntry.Invoke("memberOf");
foreach (object ob in (IEnumerable<object>)objs)
{
DirectoryEntry grpEntry = new DirectoryEntry(ob);
groups.AddLast(grpEntry.Name);
}
}

return groups;
}
The two variables that the path is made up are read from a config file that is used by another program to accomplish the same task (the program was
originally written in Java and I am porting it to C#). The mastername and masterpswd is for a testing user that should have the ability to
add and remove users from AD groups. When I run my code immediately after dirEntry's declaration all of its properties start reporting this
error in the debugger: System.Runtime.InteropServices.Exception I'm fairly certain it has something to do with the path but as I said
before there is another program that uses the same file without issues and I have been to told that the server doesn't do any sort of
encryption on port 389. An obfuscated version of the path looks like this: ldap://lxyz111.global.ad.**.com:389/dc=global,dc=ad,dc=**,dc=com

I followed the example given at this website to figure out what I needed to do: http://www.netomatix.com/UserGroupMembership.aspx


Thanks in advance for any help.

EDIT:
So after further investigation the problem is that ldap MUST be capitalized in the address so instead of ldap:// it should have been LDAP://