提问人:RobertPitt 提问时间:11/30/2010 最后编辑:RobertPitt 更新时间:1/30/2013 访问量:5913
使用 C 从 Active Directory 获取组#
Get groups from Active Directory using C#
问:
我通过以下方式从 Active Directory 获取组时遇到问题System.DirectoryServices
最初,我在域中注册的计算机上启动了我的应用程序,但由于它是一个实时域,因此我不想对 AD 进行任何写入,因此我设置了一台将 Windows XP 作为主机操作系统的计算机,并在 VM 上安装了 Windows Server 2003。
我在计算机中添加了另一个以太网端口并设置了一个交换机,其中 1 个以太网端口专用于 VM,另一个端口用于主机。
在配置了 IP 地址以使其通信后,我将应用程序转移到主机上并启动了它,但我得到了一个 .DirectoryServicesCOMException
显示用户名和密码无效的消息:(只是为了检查它不是 Active Directory,我创建了第三个虚拟机并安装了 Windows XP,我使用在 APP 中测试的凭据将其添加到域中,这很有效。
所以我认为这一定是因为运行应用程序的计算机不是域的一部分。
以下是导致问题的代码块:
public CredentialValidation(String Domain, String Username, String Password, Boolean Secure)
{
//Validate the Domain!
try
{
PrincipalContext Context = new PrincipalContext(ContextType.Domain, Domain); //Throws Exception
_IsValidDomain = true;
//Test the user login
_IsValidLogin = Context.ValidateCredentials(Username, Password);
//Check the Group Admin is within this user
//******HERE
var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);
foreach(Principal Result in Results)
{
if (Result.SamAccountName == "Domain Admins")
{
_IsAdminGroup = true;
break;
}
}
Results.Dispose();
Context.Dispose();
}
catch (PrincipalServerDownException)
{
_IsValidDomain = false;
}
}
登录对话框中的信息是这样输入的:
Domain: test.internal
Username: testaccount
Password: Password01
希望有人能在这个错误中有所启发。
更新:
检查服务器上的安全日志后,我可以看到我的登录尝试成功,但这归结为:
_IsValidLogin = Context.ValidateCredentials(Username, Password);
im 检查组之后的行导致了错误,因此主要问题是下面的代码行在未加入网络的机器上无法正常工作:
var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);
答:
根据代码片段,在调用 ValidateCredentials 之前尝试创建 PrincipalContext 时失败。此时,运行代码的线程仍在本地标识(如果位于 Web 进程中)或用于登录计算机的标识(对于 Windows 进程)下工作。其中任何一个都不会存在于 test.internal 域中。
您可能想要尝试在构造函数中包含用户名和密码的 PrincipalContext 重载。查看 http://msdn.microsoft.com/en-us/library/bb341016.aspx
评论
TEST/testaccount
testaccount@test
[email protected]
我曾经通过 C# .NET 进行过相当多的用户管理。我刚刚挖出了一些你可以尝试的方法。
以下两种方法将获取给定 SAM 帐户名称的 DirectoryEntry 对象。它采用一个 DirectoryEntry,它是要开始搜索帐户的 OU 的根目录。
另一个将为您提供用户所属组的可分辨名称列表。然后,可以使用这些 DN 搜索 AD 并获取 DirectoryEntry 对象。
public List<string> GetMemberOf(DirectoryEntry de)
{
List<string> memberof = new List<string>();
foreach (object oMember in de.Properties["memberOf"])
{
memberof.Add(oMember.ToString());
}
return memberof;
}
public DirectoryEntry GetObjectBySAM(string sam, DirectoryEntry root)
{
using (DirectorySearcher searcher = new DirectorySearcher(root, string.Format("(sAMAccountName={0})", sam)))
{
SearchResult sr = searcher.FindOne();
if (!(sr == null)) return sr.GetDirectoryEntry();
else
return null;
}
}
评论
DirectoryServices
AccountManagement
上一个:使用 Node.JS
下一个:使用正则表达式验证类/方法名称
评论
DirectoryEntry
DirectorySearcher
System.DirectoryServices
start \\server1