gpt4 book ai didi

c# - 将字符串变量传递到网络凭据构造函数中作为密码参数

转载 作者:行者123 更新时间:2023-12-04 00:41:08 25 4
gpt4 key购买 nike

我拥有的功能是允许域用户根据其 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;
}
}

关于c# - 将字符串变量传递到网络凭据构造函数中作为密码参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46762470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com