I am currently working on a part of an authorization system in our product and we have a problem with getting all groups a user is in (including nested groups).
The User MyUser
is in the following groups:
GroupA
GroupB
GroupB
is a member of GroupC
, and GroupC
is a member of GroupD
.
My desired Output would be: GroupA, GroupB, GroupC, GroupD
.
With my code, I somehow get different results for the exact same user almost every time I run my queries.
The results vary from the complete list, to only the first level or just the GroupD
missing.
My code is as following.
The part where I am parsing the string with IndexOf
is just to get the group name itself because the returned value is something like CN=GroupA,OU=Groups,OU=XYZ,DC=abc,DC=XXX
.
static void Main(string[] args)
{
var groups = new List<string>();
var searcher = new DirectorySearcher(...);
GetGroupsRecursively("MyUser", groups, searcher);
}
private static void GetGroupsRecursively(string group, List<string> groups, DirectorySearcher search)
{
search.Filter = string.Format("(cn={0})", group);
search.PropertiesToLoad.Add("memberOf");
var searchResults = search.FindAll();
foreach (SearchResult result in searchResults)
{
foreach (var dn in result.Properties["memberof"].Cast<string>())
{
var equalsIndex = dn.IndexOf("=", 1);
if (equalsIndex != -1)
{
var commaIndex = dn.IndexOf(",", 1);
var subGroup = dn.Substring(equalsIndex + 1, commaIndex - equalsIndex - 1);
if (!groups.Contains(subGroup))
{
groups.Add(subGroup);
GetGroupsRecursively(subGroup, groups, search);
}
}
}
}
}
Is there something wrong with my way of getting the groups? (Please do not suggest to use the PrincipalContext
or the like, because we can't use them here.)
Could this be a configuration issue with the AD-Server?