将字符串变量传递给Nework Credential构造函数以进行密码争用

Des*_*ind 2 c# authentication ldap environment-variables networkcredentials

我所拥有的是一个允许域用户根据其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;
    }
Run Code Online (Sandbox Code Playgroud)

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

NetworkCredential NetCred = new NetworkCredential(Environment.UserName, DomPassWord, Environment.UserDomainName);是我正在努力的,因为我可以安全地匹配域中的密码,没有硬编码,使用类似的东西DomPassWord = txtUserPW.Text.试过这SecureString条路线,但在这方面也没有成功.有任何想法吗?

Com*_*Guy 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;
    }
}
Run Code Online (Sandbox Code Playgroud)