将字符串变量传递给密码参数的网络凭据构造函数

Pass String Variable Into Nework Credential Constructor for Password Arguement

我拥有的功能允许域用户根据其 LDAP 凭据进行身份验证。但是,只要我将已知密码硬编码为原始字符串,它就可以工作……当然,这是不行的。我希望传递从我设置的 TextBox 接收到的字符串值。这是函数:

public static bool fnValLDAPCreds()
    {
        bool validation;                                 

        try
        {                

            LdapConnection ADConn = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
            NetworkCredential NetCred = new NetworkCredential(Environment.UserName, "Password123",  Environment.UserDomainName);

            ADConn.Credential = NetCred;
            ADConn.AuthType = AuthType.Negotiate;
            // the user's authenticated here; creds used to login on the domain controller.

            ADConn.Bind(NetCred);
            validation = true;
            MessageBox.Show("You were successfully authenticated against AD using LDAP!");
        }

        catch (LdapException)
        {
            validation = false;
            MessageBox.Show("Your login was unsuccesful. Try a different set of credentials.");
        }

        return validation;
    }

我尝试做的是用我的 TextBox 中的值替换,但由于它位于 static bool 中,因此我未能成功对中的控件进行任何外部引用当前上下文。我在按钮处理程序中调用这个函数来触发它。我如何交换一个 string DomPassWord 变量,它从我设置的文本框中获取它的值?

NetworkCredential NetCred = new NetworkCredential(Environment.UserName, DomPassWord, Environment.UserDomainName); 是我努力的目标,因为我可以安全地匹配域中的密码,无需硬编码,使用 DomPassWord = txtUserPW.Text 之类的东西。尝试了 SecureString 路线,但在这方面也没有成功。有什么想法吗?

您不能在静态方法中访问文本框,因为它们不是静态字段(至少从您编写的内容来看是这样)。

但是您可以简单地将您的参数传递给您的方法。把它改成这样:

public void ButtonClick(object sender, EventArgs args)
{
    // bool valid = fnValLDAPCreds(Environment.UserName, "Password123", Environment.UserDomainName);
    bool valid = fnValLDAPCreds(txtUserName.Text, txtUserPW.Text, Environment.UserDomainName);
}

public static bool fnValLDAPCreds(string username, string password, string domain)
{
    try
    {
        LdapConnection ADConn = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
        NetworkCredential NetCred = new NetworkCredential(username, password,  domain);

        ADConn.Credential = NetCred;
        ADConn.AuthType = AuthType.Negotiate;
        // the user's authenticated here; creds used to login on the domain controller.

        ADConn.Bind(NetCred);
        MessageBox.Show("You were successfully authenticated against AD using LDAP!");
        return true;
    }
    catch (LdapException)
    {
        MessageBox.Show("Your login was unsuccesful. Try a different set of credentials.");
        return false;
    }
}

有点离题,但你有没有想过AuthType.Ntlm?如果您这样做的目的只是让用户 'Charlie' 输入他的密码来确保他实际上是查理?那么你就在正确的轨道上。但是,如果您尝试使用当前用户凭据连接到 AD 作为访问 AD 本身的一种方式?那你可能想看看

ADConn.AuthType = AuthType.Ntlm;

... 并让 windows 为您处理(根本不需要让用户输入密码 - 它将使用他们当前的 windows 凭据。)