如何访问父域中用户的组?

时间:2014-02-27 05:02:09

标签: c# active-directory active-directory-group

我正在一个有两个AD域Dom1和Dom2的实例中工作。从Dom1到Dom2有单向信任,因此Dom1中的用户可以在Dom2中获得授权。

我的c#代码做得很好。

但是,在Dom2中,当我从Dom1中的用户中提取用户的组时,我什么也得不到。我从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);
                        }
                    }
                }

1 个答案:

答案 0 :(得分:0)

请尝试使用System.DirectoryServices.AccountManagement命名空间:

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();
    }
}

然后你可以按照你想要的方式找到小组:

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);