1
votes

I have a bit of code to get all of the AD groups for the user currently logged in:

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);

        // find a user
        UserPrincipal adUser = UserPrincipal.FindByIdentity(ctx, user);

        if (adUser == null)
        {
            Logger.Error("Could not find related Active Directory user");
            return;
        }
        GetUserDetailsFromGroupMembership(adUser.GetGroups().Select(g => g.Name));

This will get all the groups the current user is part of on its registered domain. My username is part of the "EUR" domain, but I also have memberships on the "USA" domain. How do I also query groups in the other domains?

1

1 Answers

2
votes

GetGroups() gets all the groups from domains in the same forest, so I have to assume that your two domains are not in the same forest, but are trusted by each other.

I don't know of a way to do this with the AccountManagement namespace, but this is how you would do it with DirectorySearcher.

When accounts get added to groups on an external, trusted domain, they show up as Foreign Security Principal objects, which contain the SID of the account. So that's what you have to search for. You already have the account in the adUser variable, so I'm using adUser.Sid here.

I assume you will always be searching the one other domain, so you can hard code the distinguishedName of the other domain in the first line.

var otherDomainDN = "DC=usa,domain,DC=com";
var ds = new DirectorySearcher(new DirectoryEntry($"LDAP://{otherDomainDN}"),
    $"(&(objectClass=group)(member=CN={adUser.Sid},CN=ForeignSecurityPrincipals,{otherDomainDN}))");
ds.PropertiesToLoad.Add("cn");

var otherDomainGroups = new List<string>();
foreach (SearchResult g in ds.FindAll()) {
    otherDomainGroups.Add(g.Properties["cn"][0].ToString());
}

After this, otherDomainGroups will be a list of the names of the other groups.