title: How to check if user is a member of crossdomain group in ldap?
body: <p>I have two AD domain: domain1 и domain2.<br/>
  I created group GlobalGroup inside domain1, and added another group Domain1Group inside GlobalGroup. <br/>
  I have two users: user1 и user2 and group Domain2Group in domain2.<br/> 
  Between domain1 and domain2 was set two-way trust. And I added Domain2Group in GlobalGroup.<br/> 
  User1 is a member of Domain1Group, and user2 is a member of Domain2Group.<br/>
  So now I need to check if they both are members of GlobalGroup.<br/></p>
  
  <p><a href="https://www.gabescode.com/active-directory/2018/09/13/one-user-is-member-of-a-group.html" rel="nofollow noreferrer">Here</a> I found how to find if user is member of some group from another domain.
  My function (below) works perfectly for user1. For user2 it returns false.<br/></p>
  
  <p>GroupPrincipal.GetMemebers(true) will return user2, but it is very slow (minutes on prod) and I can't use it.<br/></p>
  
  <p>What did I miss? Is it in code or in domain's settings?<br/></p>
  
  <p>Code sample:</p>
  
  <pre><code>private static bool IsUserInGroup(UserPrincipal user, DirectoryEntry group, bool recursive)
          {
              group.RefreshCache(new[] {"distinguishedName", "groupType"});
              var recursiveFilter = recursive ? ":1.2.840.113556.1.4.1941:" : "";
              var filter = string.Format("(member{0}={1})", recursiveFilter, user.DistinguishedName);
              var groupDN = (string)group.Properties["distinguishedName"].Value;
  
              if (((int)group.Properties["groupType"].Value &amp; 8) == 0)
              {
                  var groupDomainDN = groupDN.Substring(groupDN.IndexOf(",DC=", StringComparison.Ordinal));
                  filter = string.Format("(|{0}(member{1}=CN={2}, CN=ForeignSecurityPrincipals{3}))", filter, recursiveFilter, user.Sid, groupDomainDN);
              }
  
              var searcher = new DirectorySearcher
              {
                  Filter = filter,
                  SearchRoot = group,
                  PageSize = 1,
                  SearchScope = SearchScope.Base
              };
  
              searcher.PropertiesToLoad.Add("cn");
              return searcher.FindOne() != null;
          }
  </code></pre>