我有一系列应用程序,它们都使用我创建的相同的 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;
}
}
这不是您正在等待的答案,但我希望它能有所帮助。
First;您假设您的代码在域中工作,但我不知道它在哪里照顾用户'主要群体'。如果您选择一个组作为“用户主体组',该组不再是成员属性的一部分。
Second;根据我的理解,一种查看用户是否存在于组中的方法(我希望不是唯一的方法,但我仍在寻找)是“递归地' 在 ' 中查找用户 DNmember' 的属性group' 对象。因此,就您的情况而言,您可以询问您的域和其他域。您可以为每个域执行一次搜索。这是这样一个示例'递归单次搜索'使用控制:
/* 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();
备注:例如,您可以使用更准确的过滤器来排除通讯组。
编辑(回答评论问题):
First: 需要证件吗?如果请求是从属于该域或已批准域的计算机完成的,我会说不。
第二和第三:是的过滤器由 Microsoft 记录在AD 搜索过滤器语法 http://msdn.microsoft.com/en-us/library/aa746475%28v=vs.85%29.aspx。我编写这个过滤器的方式是从样本中推导出来的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)