C# WINFORM Active Directory:如果登录成功,则访问另一个表单

本文关键字:访问 另一个 表单 成功 登录 Active WINFORM Directory 如果 | 更新日期: 2023-09-27 17:57:05

我想从具有登录文本框和密码文本框以及登录按钮的窗体创建一个控件。当我输入活动目录帐户名及其密码时,我想转到另一个表单。有人可以帮助我解决这个问题。在此代码示例中,我选择了仅登录帐户。我想选择它并输入密码,然后通过示例从表单(登录)转到表单(用户界面)来访问目标表单。

 private void radiobtnAD_CheckedChanged(object sender, EventArgs e)
    {
        if (radiobtnAD.Checked)
        {
           try
        {
            string filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
            string[] propertiesToLoad = new string[1] { "name" };

            using (DirectoryEntry root = new DirectoryEntry("LDAP://DOMAIN"))
            using (DirectorySearcher searcher = new DirectorySearcher(root, filter, propertiesToLoad))
            using (SearchResultCollection results = searcher.FindAll())
            {
                foreach (SearchResult result in results)
                {
                    string name = (string)result.Properties["name"][0];
                    comboBox1.Items.Add(name);
                }
            }
        }
        catch
        {
        } 
        }
    }

C# WINFORM Active Directory:如果登录成功,则访问另一个表单

这是您的代码,经过编辑。

  1. 验证文本框 (!string.空)。
  2. 验证凭据。
  3. 根据用户类型显示所需的表单。

当你正确地拆分代码时,它就像馅饼一样容易。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LibXmlSettings.Settings;
using Microsoft.ApplicationBlocks.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.DirectoryServices;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.DirectoryServices.AccountManagement;
namespace GestionnaireDesPlugins
{
    public partial class Login : Form
    {
        public Login(string accountName, string accountPassword)
        {
            InitializeComponent();
        }
        private void LoginOnClick(object sender, EventArgs e)
        {
            if (IsValid())
            {
                GetUser();
                // Do whatever you want
                ShowForm();
            }
        }
        private void GetUser()
        {
            try 
            {            
                LdapConnection connection = new LdapConnection("AD");
                NetworkCredential credential = new NetworkCredential(txtboxlogin.Text, txtboxpass.Text);
                connection.Credential = credential;
                connection.Bind();
            }
            catch (LdapException lexc)
            {
                String error = lexc.ServerErrorMessage;
                MessageBox.Show("error account or password.");
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }
        private bool IsValid()
        {
            // Check if the user haven't chosen an account
            if (!string.IsNullOrEmpty(txtboxlogin.Text) { return false; }
            // Check if the user haven't chosen an account
            if (!string.IsNullOrEmpty(txtboxpass.Text)) { return false; }
            // Check if the user haven't chosen an account
            if (!string.IsNullOrEmpty(comboBox1.Text)) { return false; }
            // Check if the password TextBox is empty
            if (!string.IsNullOrEmpty(textBox1.Text)) { return false; }
            using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
            {
                // validate the credentials
                bool isValid = pc.ValidateCredentials(txtboxlogin.Text, txtboxpass.Text);
            }
            return isValid;
        }
        private void ShowForm()
        {
            if (txtboxlogin.Text == "WantedAdminUser")
            {
                using (AdminForm form2 = new AdminForm())
                   form2.ShowDialog();
                Show(); 
            }
            else
            {
                using (user userform = new user())
                    userform.ShowDialog();
                Show();
            }
        }
    }
}

如前所述,由于您不熟悉 C#,因此这里有一些建议:

  1. 拆分代码:方法必须简短,并按用途分隔。这对您和任何处理您的代码的人来说都更容易
  2. 管理异常
  3. 释放对象
  4. 小心这个txtboxlogin.Text == "WantedAdminUser"很危险。

因此,您有一个窗体,其中包含填充帐户名称的 ComboBox、一个用于密码输入的文本框和一个用于打开新窗体的按钮。

将文本框的属性PasswordChar设置为所需的掩码字符:

textBox1.PasswordChar = '*';

通过在设计器中双击登录按钮,为登录按钮创建新的单击方法。它应该创建一个新的处理程序:

private void loginButton_Click(object sender, EventArgs e)
{
   // Check if the user haven't chosen an account
   if (comboBox1.Text == "") { return; }
   // Check if the password TextBox is empty
   if (textBox1.Text == "") { return; }
   // Create a new method for checking the account and password, which returns a bool
   bool loginSuccess = CheckUserInput(comboBox1.Text.Trim(), textBox1.Text);
   if (loginSuccess)
   {
      // Create a new instance of your user-interface form. Give the account name and password
      // to it's constructor
      UserForm newForm = new UserForm(comboBox1.Text.Trim(), textBox1.Text.Trim()))
      // Show the created UserForm form
      newForm.Show();
      // Close this login form
      this.Close();
   }
}

编辑用户窗体构造函数以采用 2 个字符串参数:

public UserForm(string accountName, string accountPassword)
{
   InitializeComponent();
   // ...
}

添加 2 个字符串参数是可选的。希望这回答了你的问题。

"用户输入查核"示例:

private bool CheckUserInput(string account, string password)
{
   // your conditions...
   return true;
}

这是我的应用程序的代码:

  using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using LibXmlSettings.Settings;
    using Microsoft.ApplicationBlocks.Data;
    using System.Data.Sql;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;
    using System.DirectoryServices;
    using System.IO;
    using System.Linq.Expressions;
    using System.Runtime.InteropServices;
    using System.DirectoryServices.AccountManagement;
    namespace GestionnaireDesPlugins
public partial class Login : Form
    {
        public Login(string accountName, string accountPassword)
        {
            InitializeComponent();
        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            using (var context = new PrincipalContext(ContextType.Domain, "Domain"))
                {
                    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                    {
                        foreach (var result in searcher.FindAll())
                        {
                            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                           comboBox1.Items.Add(de.Properties["samAccountName"].Value);
                           comboBox1.Sorted = true;
                        }
                    }
                }
 // Check if the user haven't chosen an account
   if (comboBox1.Text == "") { return; }
   // Check if the password TextBox is empty
   if (textBox1.Text == "") { return; }
   // Create a new method for checking the account and password, which returns a bool
   bool loginSuccess = CheckUserInput(comboBox1.Text.Trim(), textBox1.Text);
   if (loginSuccess)
   {
      // Create a new instance of your user-interface form. Give the account name and password
      // to it's constructor
      UserForm newForm = new UserForm(comboBox1.Text.Trim(), textBox1.Text.Trim()))
      // Show the created UserForm form
      newForm.Show();
      // Close this login form
      this.Close();
   }
}
}

我解决了我正在寻找的东西

private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                LdapConnection connection = new LdapConnection("AD");
                NetworkCredential credential = new NetworkCredential(txtboxlogin.Text, txtboxpass.Text);
                connection.Credential = credential;
                connection.Bind();
               MessageBox.Show("You are log in");
               Hide();
               if (txtboxlogin.Text == "WantedAdminUser")
               {
               using (AdminForm form2 = new AdminForm())
                   form2.ShowDialog();
               Show(); 
               }
               else
               {
                   using (user userform = new user())
                       userform.ShowDialog();
                   Show();
               }
            }
            catch (LdapException lexc)
            {
                String error = lexc.ServerErrorMessage;
                MessageBox.Show("error account or password.");
            }
            catch (Exception exc)
            {
                MessageBox.Show(Convert.ToString(exc));
            }