Getting a list of group memberships (memberOf) in Active Directory

I will be back with my Active Directory tool ...

I am trying to list groups in the member attribute of the user. The following is the function I am using:

public static DataTable ListGroupsByUser(string selectedOu) { DataTable groupListByUser = new DataTable(); String dom = "OU=" + selectedOu + ",OU=XXX,DC=XXX,DCXXX,DC=XXX,DC=XXX"; DirectoryEntry directoryObject = new DirectoryEntry("LDAP://" + dom); DataColumn column; DataRow row; column = new DataColumn(); column.ColumnName = "ID"; groupListByUser.Columns.Add(column); column = new DataColumn(); column.ColumnName = "User"; groupListByUser.Columns.Add(column); column = new DataColumn(); column.ColumnName = "Groups"; groupListByUser.Columns.Add(column); int i = 1; foreach (DirectoryEntry child in directoryObject.Children) { row = groupListByUser.NewRow(); groupListByUser.Rows.Add(row); row["ID"] = i++; if (child.Properties["memberOf"].Value != null) { row["User"] = child.Properties["sAMAccountName"].Value.ToString(); row["Groups"] = child.Properties["memberOf"].Value.ToString(); } else { row["Groups"] = "blabla"; } } return groupListByUser; } 

It returns the correct group for users belonging to only one group. As soon as there is more than one group, it returns System.Object [].

How do I do to see all groups?

+6
source share
2 answers

If you are using .NET 3.5 and above, you should check the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read more here:

Basically, you can define the context of a domain and easily find users and / or groups in AD:

 // set up domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // find a user UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName"); if(user != null) { var groups = user.GetGroups(); // or there also: //var authGroups = userByEmail.GetAuthorizationGroups() } 

Calls to GetGroups() or GetAuthorizationGroups() will return nested group memberships too, so you no longer need to hunt for these nested memberships!

The new S.DS.AM makes it very easy to play with users and groups in AD!

+4
source

The problem is your Properties["memberOf"].Value.ToString() .

I did a little investigation, and this code worked for me:

 var memberGroups = child.Properties["memberOf"].Value; if (memberGroups.GetType() == typeof(string)) { row["Groups"] = (String)memberGroups; } else if (memberGroups.GetType().IsArray) { var memberGroupsEnumerable = memberGroups as IEnumerable; if (memberGroupsEnumerable != null) { var asStringEnumerable = memberGroupsEnumerable.OfType<object>().Select(obj => obj.ToString()); row["Groups"] = String.Join(", ", asStringEnumerable); } } else { row["Groups"] = "No group found."; } 

This is not very nice, but it works and provides an opportunity for further improvements .; -)

+4
source

Source: https://habr.com/ru/post/909534/


All Articles