Search code examples
c#asp.netfilteractive-directorydirectoryentry

How I can find a user in Active Directory Group with SubGroups?


I have a Problem with ASP.NET and Active Directory.

I want to find out whether the User is in a Groupe of the Active Directory and if he is in this Group he can see more. For this I write a Function with a filterstring. The Problem is that in our company we switch the Groups and the structure is not static. For this I search the Group first and than I search a user in the Group with the parameter member-of...

here is the structure of our AD:

enter image description here

Here is my Code for saerch the group:

public string GetGroup(string groupname)
        {
            string path = "<OurDomain>";

            DirectoryEntry rootEntry = new DirectoryEntry(path);

            DirectorySearcher srch = new DirectorySearcher(rootEntry);
            srch.SearchScope = SearchScope.Subtree;

            srch.Filter = "(&(objectCategory=Group)(name=" + groupname + "))";

            SearchResult resFilter = srch.FindOne();

            string filterpath = resFilter.Path;

            return filterpath; 
        }

My method for find the user:

public bool IsUserInGroup(string username,string groupepath) 
        {
            string path = "<OurDomain>"; 

            DirectoryEntry rootEntry = new DirectoryEntry(path);

            DirectorySearcher srch = new DirectorySearcher(rootEntry);
            srch.SearchScope = SearchScope.Subtree;

            srch.Filter = "(&(objectClass=user)(sAMAccountName=*" + username + "*)(memberof=CN=GastzugangUser,OU=SubFolderB,OU=FolderB,DC=company,DC=com))";


            SearchResultCollection res = srch.FindAll();

            if (res == null || res.Count <= 0)
            {
                return false;
            }
            else
            {
                return true; 
            }
        }

How I can search a User in the SubGroups of a Group and that dynamic? :(


Solution

  • Didn't try that but does adding this to the filter help? http://ldapwiki.willeke.com/wiki/1.2.840.113556.1.4.1941

    e.g.

    (&(objectClass=user)(sAMAccountName=*" + username + "*)(memberof:1.2.840.113556.1.4.1941:=CN=GastzugangUser,OU=SubFolderB,OU=FolderB,DC=company,DC=com))";