【发布时间】:2011-07-06 20:09:27
【问题描述】:
我有一系列应用程序都使用我创建的相同 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;
}
}
【问题讨论】:
标签: c# .net active-directory .net-2.0 ldap