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

我有一系列应用程序都使用我创建的相同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; } } 

这不是你正在等待的答案,但我希望它可以提供帮助。

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

第二 ; 在我的理解中,一种方式(我希望不是唯一一个,但我仍然在寻找),如果一个用户,在组中存在的方式是’ 重复 ‘在’ member ‘属性中查找用户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(); 

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


编辑(回答评论问题):

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

第二个和第三个 :Microsoft在AD搜索filter语法中记录了filter 。 我写这个filter的方式是从样本中扣除。