【发布时间】:2012-03-20 19:02:02
【问题描述】:
我有一个代码来检查用户是否是组的成员。 我在登录时使用它。
请注意我有一个域用户和本地用户,例如。 testdomain\administrator 和 administrator。
这是我使用的代码:
using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./" + userGroupName + ",group"))
{
foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
{
using (DirectoryEntry memberEntry = new DirectoryEntry(member))
{
string completeName = memberEntry.Name;
DirectoryEntry domainValue = GUIUtility.FindDomain(memberEntry);
if (domainValue != null)
{
completeName = domainValue.Name + "\\" + memberEntry.Name;
}
Global.logger.Info("completeName from " + userGroupName + " = " + completeName);
if (userName.Equals(completeName, StringComparison.InvariantCultureIgnoreCase))
{
Global.logger.Debug("IsUserPartOfWindowsGroup returned True with username =" + userName + " , UserGroupName = " + userGroupName);
return true;
}
}
}
Global.logger.Debug("IsUserPartOfWindowsGroup returned false for username =" + userName + " , UserGroupName = " + userGroupName);
return false;
}
这段代码有效,但是
DirectoryEntry domainValue = GUIUtility.FindDomain(memberEntry);
在我看来,在分析器中花费了很多时间。有没有更好/更快的方法来处理这个问题?
public static DirectoryEntry FindDomain(DirectoryEntry memberEntry)
{
if (memberEntry.Parent != null)
{
if (memberEntry.Parent.SchemaClassName.Equals("domain", StringComparison.InvariantCultureIgnoreCase))
{
return memberEntry.Parent;
}
}
return null;
}
另一种方式:
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, Password);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))";
SearchResult result = mySearcher.FindOne();
Global.logger.Info("result == " + result.Path);
foreach (string GroupPath in result.Properties["memberOf"])
{
if (GroupPath.Contains(adminGroupName))
{
Global.logger.Info(compUsrNameForEncryption + "exists in " + adminGroupName);
}
}
【问题讨论】:
-
如果我们知道
GUIUtility.FindDomain是什么,我们可能会提供更好的帮助。此外,新的(ish)System.DirectoryServices.AccountManagement 类使这类事情变得更加简单。 -
Related question,my answer 中的代码可能也会对您有所帮助。
-
嘿 babcock.. 我添加了 finddomain 功能。如果用户不属于域怎么办?
-
您确定
FindDomain是什么在消耗您的周期吗?它并没有真正做任何事情。 -
不是域的一部分,这意味着他们只是本地用户?
标签: c# asp.net windows login active-directory-group