title: Cross domain active directory group membership
body: <p>I have seen a few questions that are like mine, but none that actually apply.  The problem I am facing is:</p>
  
  <p>I need to get group membership of User with:</p>
  
  <ul>
  <li>Group in Domain B</li>
  <li>User in domain A.</li>
  <li>Service in domain B.</li>
  <li>Forrest to Forrest 2-way trust.</li>
  </ul>
  
  <p>User attaches to service and service gets WindowsIdentity object with SID, name, etc.</p>
  
  <p>In order to get group membership, I am using a UserPrincipal object.  In order to get that, you need a PrincipalContext object.  The constructor for the PrincipalContext object needs the FQDN of the domain (i.e. A.some.domain.com).  The WindowsIdentity object has the NetBios domain name in the username (i.e. A\User), but I cannot see a way to get the DNS name.</p>
  
  <p>Here is an example of code that has the DNS name HARD CODED, that works, but I need to take out the hard coded part.</p>
  
  <p>-- WindowsIdentity wi (passed into the method) --</p>
  
  <pre><code>PrincipalContext context = new PrincipalContext(ContextType.Domain, "A.some.domain.com");
  UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.Sid, wi.User.ToString());
  </code></pre>
  
  <p>I have another solution that uses impersonation, using System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain().Name, but that is not acceptable because impersonation may not be available.  I need a solution that will work with <strong><em>TokenImpersonationLevel.Identification</em></strong></p>
  
  <p>I have spent several days scouring MSDN and Google (including Stack Overflow) to no avail.</p>