如何查询一个域的用户是否是另一个AD域中的组的成员?

RLH*_*RLH 6 .net c# ldap active-directory .net-2.0

我有一系列应用程序都使用我创建的相同C#,.Net 2.0代码来检查并查看用户是否是Active Directory组的成员.

直到最近,当我将另一个可信赖的AD域中的用户添加到我的AD组之一时,我的代码没有遇到任何问题.我的问题是如何检查用户是否是Active Directory组的成员,无论他们的域名是什么.换句话说,它们可能与我的组在同一个域中,也可能不在同一个域中.下面是我编写并使用多年来搜索以查看用户是否在Active Directory组中的代码.我不确定我在哪里修改了这段代码,但我认为它来自MSDN文章.此外,解决方案必须是.Net 2.0框架.我找到了很多可能适用于.Net 3.5中此问题的答案.不幸的是,这对我的方案不起作用.

//This method takes a user name and the name of an AD Group (role).  
//Current implementations of this method do not contain the user's domain 
//with userName, because it comes from the Environment.UserName property.
private static bool IsInRole(string userName, string role)
{
    try
    {
        role = role.ToLowerInvariant();
        DirectorySearcher ds = new DirectorySearcher(new DirectoryEntry(null));
        ds.Filter = "samaccountname=" + userName;
        SearchResult sr = ds.FindOne();
        DirectoryEntry de = sr.GetDirectoryEntry();
        PropertyValueCollection dir = de.Properties["memberOf"];
        for (int i = 0; i < dir.Count; ++i)
        {
            string s = dir[i].ToString().Substring(3);
            s = s.Substring(0, s.IndexOf(',')).ToLowerInvariant();
            if (s == role)
                return true;
        }
        throw new Exception();
    }
    catch
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

JPB*_*anc 1

这不是您正在等待的答案,但我希望它能有所帮助。

第一的; 您假设您的代码在域中工作,但我看不到它在哪里处理用户“主体组”。如果您选择一个组作为“用户主体组”,则该组不再是成员属性的一部分。

第二; 根据我的理解,查看用户是否存在于组中的一种方法(我希望不是唯一的方法,但我仍在寻找)是“反复”在“成员”属性中查找用户 DN “”对象。因此,就您的情况而言,您可以询问您的域和其他域。您可以为每个域执行一次搜索。以下是使用控制的“递归一次性搜索”的示例:

/* Connection to Active Directory
 */
string sFromWhere = "LDAP://WIN-COMPUTER:389/";
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "dom\\user", "password");

/* To find all the groups that "user1" is a member of :
 * Set the base to the groups container DN; for example root DN (dc=dom,dc=fr) 
 * Set the scope to subtree
 * Use the following filter :
 * (member:1.2.840.113556.1.4.1941:=cn=user1,cn=users,DC=x)
 */
DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
dsLookFor.Filter = "(member:1.2.840.113556.1.4.1941:=CN=user1 Users,OU=MonOu,DC=dom,DC=fr)";
dsLookFor.SearchScope = SearchScope.Subtree;
dsLookFor.PropertiesToLoad.Add("cn");

SearchResultCollection srcGroups = dsLookFor.FindAll();
Run Code Online (Sandbox Code Playgroud)

备注:例如,您可以使用更准确的过滤器来排除通讯组。


编辑(回答评论问题):

第一:需要凭证吗?如果请求是从属于该域或已批准域的计算机完成的,我会说不。

第二和第三:“是”过滤器由 Microsoft 在AD 搜索过滤器语法中记录。我编写这个过滤器的方式是从样本中推导出来的。