使用C#从Active Directory获取组

Rob*_*itt 7 c# active-directory active-directory-group

我在通过Active Directory获取组时遇到问题 System.DirectoryServices

最初我在一个在域上注册的计算机上启动了我的应用程序,但由于它是一个活动域,我不想对AD做任何写入,所以我设置了一台Windows XP作为主机操作系统的机器,并在VM上安装了Windows Server 2003.

我在机器中添加了另一个以太网端口并设置了一个交换机,1个以太网端口专用于VM,另一个端口用于主机.

在配置IP地址以使它们通信之后,我将我的应用程序转移到主机上并将其启动,但我得到了一个DirectoryServicesCOMException.

随着用户名和密码无效的消息:(只是为了检查它是不是活动目录我创建了第三个虚拟机并安装了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;
     }
 }
Run Code Online (Sandbox Code Playgroud)

正在输入登录对话框中的信息,如下所示:

Domain: test.internal
Username: testaccount
Password: Password01
Run Code Online (Sandbox Code Playgroud)

希望有人可以解释这个错误.


更新:

检查服务器上的安全日志后,我可以看到我的登录尝试成功,但这归结为:

_IsValidLogin = Context.ValidateCredentials(Username, Password);
Run Code Online (Sandbox Code Playgroud)

我检查组之后的行导致错误,因此主要问题是下面的代码行无法从未加入网络的计算机正常工作:

var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);
Run Code Online (Sandbox Code Playgroud)

Joh*_*sen 2

根据您的代码片段,当您尝试在调用 ValidateCredentials 之前创建 PrimaryContext 时会失败。此时,运行代码的线程仍在本地身份(如果您位于 Web 进程中)或您登录计算机所用的身份(对于 Windows 进程)下工作。其中任何一个都不会存在于 test.internal 域中。

您可能想尝试重载PrincipalContext,其中在构造函数中包含用户名和密码。请参阅http://msdn.microsoft.com/en-us/library/bb341016.aspx