我有一系列应用程序,它们都使用我创建的相同 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;
}
}
最佳答案
这不是您要的答案,但希望对您有所帮助。
首先 ;您假设您的代码在域中工作,但我看不到它在哪里处理用户“主要组”。如果您选择一个组作为“用户主体组”,则该组不再是成员属性的一部分。
第二 ;据我了解,如果用户出现在一个组中,一种方式(我希望不是唯一的,但我仍在寻找)是“反推”寻找用户“组”对象的“成员”属性中的 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();
备注:例如,您可以使用更准确的过滤器来排除通讯组。
编辑(回答评论问题):
首先:是否需要凭据?如果请求是从属于该域或已批准域的计算机完成的,我会拒绝。
第二个和第三个:是的过滤器由 Microsoft 在 AD Search Filter Syntax 中记录.我编写此过滤器的方式是从样本中扣除。
关于c# - 如何查询一个域的用户是否是另一个AD域中的组的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6602297/