c# winform active directory: acces to another form if login succes

一个人想着一个人 提交于 2020-01-11 13:33:34

问题


i want to create a control from a form where i have login textbox and password textbox, and login button. when i will enter the active directory account name and its password i want to go to another form. someone can help me with this please. in this code example i chose the account for login only. i want to chose it and type the password and go the destination form by exemple from form (login) to form (user interface).

 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
        {
        } 
        }

    }

回答1:


Here is your code, edited.

  1. Verify the textboxes (!string.Empty).
  2. Validate credentials.
  3. Display the form you want depending on user type.

It is easy as pie, when you correctly split your code.

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();
            }
        }
    }
}

As said previously, as you are new in C#, here are some advice:

  1. Split your code: methods must be short and separated by purpose. It's easier for you and for any who works on your code
  2. Manage the exception
  3. Dispose objects
  4. Take care about this txtboxlogin.Text == "WantedAdminUser" it's dangerous.



回答2:


So you have a form with ComboBox filled with account names, a TextBox for password input, and a Button for opening the new form.

Set the TextBox's property PasswordChar to desired mask character:

textBox1.PasswordChar = '*';

Create a new click method for your login-button by double clicking it in the designer. It should create a new handler:

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();
   }
}

Edit your UserForm form constructor to take 2 string parameters:

public UserForm(string accountName, string accountPassword)
{
   InitializeComponent();

   // ...
}

Adding the 2 string parameters is optional. Hope this answered your question.

Example of "CheckUserInput":

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



回答3:


this is the code of my app :

  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();
   }
}
}



回答4:


i solved what i was looking for

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));
            }


来源:https://stackoverflow.com/questions/22916260/c-sharp-winform-active-directory-acces-to-another-form-if-login-succes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!