Link to home
Start Free TrialLog in
Avatar of Member_2_8189690
Member_2_8189690

asked on

unable to get AD groups from cross subdomain or child domain using AD C#

Hi ,
For one of my client their AD structure is like
Domain architecture example :

•      xyz.com (Main Domain)
1.      abc.xyz.com (Subdomain)
      abc.xyz/User1  --> user in abc sub domain
      abc.xyz/User2  -->user in abc sub domain
      ADGrp1  --> Ad group in this abc domain
      ADGrp2  --> Ad group in this abc domain


2.      test.xyz.com (Subdomain)
    test.xyz/User3    --> user in test sub domain
   test.xyz/User4    --> user in test sub domain
    ADGrp3  --> Ad group in this test domain
    ADGrp4  --> Ad group in this test domain

Now problem arises when in my web.config ADGrop3 is configured and and ADGrp3 consist od cross sub domain abc.xyz\user1 and user is not getting acces.

 private List<string> GetGroups()
        {
                  List<string> groups = new List<string>();
                  if (string.IsNullOrEmpty(domainName)) return groups;
           
            using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName))
            {
                try
                {
                    UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, userName);
                    if (user != null)
                    {
                        PrincipalSearchResult<Principal> groupResults = user.GetGroups(principalContext);
                                    groups = getItems(groupResults);
                    }
                }
                catch (Exception ex)
                {
                    string errorMessage = "AD error: " + ex.Message;
                    if (ex.InnerException != null)
                    {
                        errorMessage += "with inner exception message: " + ex.InnerException.Message;
                    }

                    throw new xyz(errorMessage, ex);
                }
            }

            return groups;
        }


      private List<string> getItems(PrincipalSearchResult<Principal> itemResults , bool userItem =true)
            {
                  List<string> groupItems = new List<string>();
                  // expand to enumerator and enumerate manually rather than using LINQ or foreach
                  // this works around rare cases where enumerating through the groups throws an exception due to not handling an element in error correctly
                  // http://support.microsoft.com/kb/969166/en-us does not appear to correct this issue
                  IEnumerator<Principal> enumerator = itemResults.GetEnumerator();
                  bool success;

                  do
                  {
                        try
                        {
                              success = enumerator.MoveNext();
                        }
                        catch
                        {
                              break;
                              // truncate the returned results to whatever was retrieved before the failure. See
                              //https://blogs.msdn.com/b/dsadsi/archive/2010/12/14/title-system-directoryservices-accountmanagetment-userprincipal-getgroups-will-throws-comexception-error-0x5011-s-ads-errorsoccurred-while-enumerating-the-principalsearchresult-collection.aspx?Redirected=true
                              // - the failing element is likely the last one
                        }

                        if (success)
                        {
                              Principal userResult = enumerator.Current;
                              string addname = string.Empty;
                              if (userResult != null && !string.IsNullOrEmpty(userResult.Name))
                              {
                                    if (userItem)
                                    addname = userResult.Name.ToLower(CultureInfo.CurrentCulture);
                                    else
                                      addname = string.Format("{0}\\{1}", userResult.Context.Name.ToUpper(CultureInfo.CurrentCulture), userResult.SamAccountName.ToLower(CultureInfo.CurrentCulture));
                                    groupItems.Add(addname);
                              }
                        }
                  } while (success);
                  return groupItems;
            }
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Hi Bharti,

Does your code throw any error? or it simply does not return the results from sub domains?

Regards,
Chinmay.
Avatar of Member_2_8189690
Member_2_8189690

ASKER

Thank you fro your instant reply .
It,s not throwing any error ,its not returning groups not found.
We are getting domain nad user name from login by splittingit like -- > abc.xyz\user1 .So , domain name will be abc.xyz and username will be user1 .

So , in this scenario code will query for groups available in abc.xyz (child sub domain )have user1 as memeber but ADgroups in web.config is ADgrp3 which is in other child domain(i.e test.xyz).

I do have tried few code using Directory seracher as well principal context but buth are not giving me output in all scenario .
Like -- application can be deployed in any of the (Parent and child domain forest) and they can access from any child domains .
My answer below is based on limited information that I have from your code and comments. I am making some assumptions as well. Please clarify/correct in case I am taking a wrong direction.

If you want to list all the information from all the domains, the code should execute in the context of an account that has permission to query all the directory object. Please consult with the domain administrator/s of your client as well. They might have group policies which can block such access. If nothing works, worst case scenario, only to try - I don't recommend this for a production usage - you could temporarily execute this code with an enterprise admin or domain admin account - just to see if it is a permission issue. Again, this is a very sensitive topic and might not sit well with your customer.

Also, you just want to list the groups right? is there anything else you would want to do after the groups are listed?

PS: I suggest you remove the name of the client's domain and any other sensitive information. It generally violates your NDA with that organization and puts you/your organization in a bad position.
Have you tried DirectoryEntry Class (System.DirectoryServices) ?
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.