简体   繁体   中英

How do I access groups of a user in a parent domain?

I'm working in an instance where there are two AD domains Dom1 and Dom2. There is a one way trust from the Dom1 to the Dom2 so that users in Dom1 can be authorized in Dom2.

My c# code does this just fine.

However, in Dom2 when I go to pull the user's groups from a user in Dom1 I don't get anything. I do get a list of groups from users that exist in Dom2.

            _DE.Path = "LDAP://RootDSE";
        string szDomain = (string)_DE.Properties["defaultNamingContext"][0];
        string obEntry = "LDAP://" + szDomain;
        SearchResult res = ADExists("UserPrincipalName=" + szUPN, "User");
        try
        {
            if (res != null)
            {
                _DE.Path = res.Path;
                //szUserDN = res.Path;
                if (_DE.Properties["memberOf"].Count > 1)
                {
                    object[] groups = (object[])_DE.Properties["memberOf"].Value;
                    if (groups != null)
                    {
                        foreach (object group in groups)
                        {
                            string szGroup = group.ToString();
                            DataRow drAdd = dtGroups.NewRow();
                            drAdd["GroupName"] = group;
                            dtGroups.Rows.Add(drAdd);
                        }
                    }
                }

Try using the System.DirectoryServices.AccountManagement namespace instead:

static GroupPrincipal[] GetUserAuthorisationGroups(string userPrincipalName)
{
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.UserPrincipalName, userPrincipalName))
    {
        return user.GetAuthorizationGroups().OfType<GroupPrincipal>().ToArray();
    }
}

Then you can find groups by whatever way you want:

GroupPrincipal[] groups = GetUserAuthorisationGroups(szUPN);

bool searchBySid = groups.Any(g => g.Sid == groupSid);
bool searchByDN = groups.Any(g => g.DistinguishedName == groupDN);
bool searchByName = groups.Any(g => g.Name == groupName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM