2

我正在使用 Active Directory API,并尝试使用以下代码连接到服务器:

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, (server + ":" + port), loginUsername, loginPassword);

每当传递了无效的登录用户名或密码时,都不会引发整个语句的异常,但以下代码会继续执行。在调试时,我发现PrincipalContext该类却抛出了一个错误,如下所示:

在此处输入图像描述

这是类中包含的两个属性。在进一步检查“ConnectedServer”属性时,调试器中会显示以下内容:

在此处输入图像描述

我的问题是,由于没有从外部抛出错误,我不确定如何实际检查此错误。如果用户名或密码无效,我想显示一条简单的错误消息-基本上是找到一种方法来检查是否引发了上述错误。

如何才能做到这一点?

4

4 回答 4

1

的类System.DirectoryServices.AccountManagement是不同的执行。它不会尝试连接到 Active Directory 服务器,直到它必须这样做。ValidateCredentials方法是强制检查的方法,来自 MSDN :

ValidateCredentials 方法绑定到构造函数中指定的服务器。如果用户名和密码参数为空,则验证构造函数中指定的凭据。如果构造函数中没有指定凭据,并且用户名和密码参数为空,则此方法验证当前主体的默认凭据。

所以你需要做的就是

using(PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, (server + ":" + port), loginUsername, loginPassword))
{
    //This will force the connection to the server and validate that the credentials are good
    //If the connection is good but the credentals are bad it will return "false", if the connection is bad it will throw a exception of some form.
    if(principalContext.ValidateCredentials(null, null))
    {
        // Rest of code here.

        //This is how you do the same check you where doing in your previous quesiton, notice that this is "userName", and "password" not "loginUsername" and "loginPassword"
        valid = principalContext.ValidateCredentials(userName,password);

    }
}
于 2013-11-11T15:19:47.510 回答
1

处理主体上下文中的任何异常的最佳方法是将代码置于 try 中,然后捕获异常,如下所示。

        string user = txtUsername.Text;
        string pass = txtPassword.Text;

        //start a try and catch method
      try
      {

       //create a principalcontext object

        var pc = new PrincipalContext(ContextType.Domain, "*****", user, pass);
         {


               //validate the user credentials
                if (pc.ValidateCredentials(user, pass))
                {
                    //create a user identity
                    UserPrincipal userp = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, user);

                    //check if the user is returned

                    if (userp != null)
                    {
                        //if user exists, return an array of authorized groups
                        var grps = userp.GetAuthorizationGroups();

                        //convert the array to a list to enable search of CIS group
                        List<string> strList = grps.Select(o => o == null ? String.Empty : o.ToString()).ToList();

                        //check for CIS group from the list
                        if (strList.Contains("CISS"))
                        {
                            //create a session variable to show the loggedin user and set the error panel to false
                            Session["username"] = user;
                            ErrorPanel.Visible = false;

                            //redirect the user to the homepage
                            Response.Redirect("appdesk/account.aspx");
                        }
                        else if (!strList.Contains("CISS"))
                        {
                            Label1.Text = "You Don't have the Rights to login to the platfrom";
                            ErrorPanel.Visible = true;

                    }
                }
                 //if the user credentials are invalid
                if (!pc.ValidateCredentials(user, pass))
                {
                    Label1.Text = "Login Failed.Incorrect Username or Password";
                    ErrorPanel.Visible = true;


                }
             }
        }
          //catch the exceptions in the try
       catch (Exception exc)
       {
                Label1.Text = exc.Message.ToString();
                ErrorPanel.Visible = true;                    

       }
于 2016-09-30T13:34:59.563 回答
0

我发现尝试将 PrincipalContext.ConnectedServer 属性分配给变量会导致异常出现:

using(var _ctx = new PrincipalContext(ContextType.Domain, server + ":" + port))
{
   try
   {
      var connectedServer = _ctx.ConnectedServer;
   }
   catch (Exception)
   {
      //do something with the caught exception
   }
}
于 2014-10-17T21:10:15.323 回答
0

一个基本的捕获不起作用?就像是:

private ADConnectResults Connect(string server, int port)
try
{
    PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, (server + ":" + port), loginUsername, loginPassword);
    return new ADConnectResults(true, principalContext);
}
catch(DirectoryServicesCOMException dex)
{
     Log(dex);
     return new ADConnectResults(false);
}
}
于 2013-11-11T15:21:02.880 回答