我所拥有的是一个允许域用户根据其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
路线,但在这方面也没有成功。有什么想法吗?
答案 0 :(得分:5)
您无法访问静态方法中的文本框,因为它们不是静态字段(至少从您编写的内容看起来如此)。
但是你可以简单地将你的参数传递给你的方法。把它改成这样的东西:
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;
}
}
答案 1 :(得分:0)
有点切,但你有没有想过AuthType.Ntlm?如果您所做的只是通过让他输入密码来确保用户'Charlie'实际上是Charlie?然后你走在正确的轨道上。但是,如果您尝试使用当前用户凭据连接到AD作为获取AD本身的方式?那你可能想看看
ADConn.AuthType = AuthType.Ntlm;
...并让Windows为您处理(无需让用户输入密码 - 它将使用当前的Windows凭据。)