How to User Authentication Against Active Directory in C#

  1. Use System.DirectoryServices.AccountManagement Namespace to Validate a User Against Active Directory in C#
  2. Use System.DirectoryServices Namespace to Validate a User Against Active Directory in C#
  3. Use System.DirectoryServices.Protocols Namespace to Validate a User Against Active Directory in C#
  4. Use ActiveDirectoryMembershipProvider.ValidateUser(String, String) Method to Validate a User Against AD in C#
How to User Authentication Against Active Directory in C#

The account authentication against Active Directory is possible by validating credentials based on the given user information and returning the result to the call method. This tutorial will teach four possible ways to authenticate or validate a user against Active Directory in C#.

Use System.DirectoryServices.AccountManagement Namespace to Validate a User Against Active Directory in C#

One of the easiest methods, if you work on the .NET 3.5 or newer versions that can verify or validate user credentials. The primary goals of this namespace are to simplify principle management operations and make them consistent regardless of the underlying directory and provide reliable results for these operations.

In general, C# developers who build directory-based applications often need to authenticate the credentials of users stored in the Active Directory, and they accomplish this task using the DirectoryEntry class to force an LDAP bind operation under the hood.

As it is extremely easy to write poor C# code that is not secure, developers must be careful to write highly-secure code. It allows you to overcome the inherent limitations in Active Directory but at the expense of writing more complicated C# code.

Example Code:

using System;
using System.Windows.Forms;
using System.DirectoryServices.AccountManagement;

namespace activeDirectoryAuthentication {
  public partial class Form1 : Form {
    string username, password;
    public Form1() {
      InitializeComponent();
    }

    // insert username in textfield by user
    private void textBox1_TextChanged(object sender, EventArgs e) {
      username = textBox1.Text;
    }

    // insert password in textfield by user
    private void textBox2_TextChanged(object sender, EventArgs e) {
      password = textBox2.Text;
    }

    // click event after the user clicks `Login`
    private void button1_Click(object sender, EventArgs e) {
      try {
        // create a connection to domain, no need to add or mention LDAP:// in domain
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "yourdomain.com")) {
          // validate the credentials
          bool isValid = pc.ValidateCredentials(username, password);
          if (isValid) {
            // User credentials validated
          } else {
            // Not authenticated
          }
        }
      } catch (Exception ex) {
        // throw an exception when a connection to the domain is unsuccessful
      }
    }
  }
}

Use System.DirectoryServices Namespace to Validate a User Against Active Directory in C#

It provides easy access to Active Directory Domain Services and contains two primary component classes, DirectorySearcher and DirectoryEntry, to use Active Directory Services Interfaces technology. It easily validates users against the Active Directory by locating and managing resources on a network regardless of their size.

It enables your applications to use a single interface to interact with diverse directions on the internet. It uses a tree structure where each node represents a set of properties, and you can use it to search, traverse, and edit the tree, as well as read/write the properties of a node.

The DirectoryEntry class encapsulates a node in the AD Domain Services hierarchy and can bind objects, read properties, and update attributes or user accounts. Use the DirectorySearcher class to perform queries against the Active Directory to validate and authenticate users.

Example Code:

using System;
using System.Windows.Forms;
using System.DirectoryServices;

namespace activeDirectoryAuthentication {
  public partial class Form1 : Form {
    string username, password;
    public Form1() {
      InitializeComponent();
    }

    // insert username in textfield by user
    private void textBox1_TextChanged(object sender, EventArgs e) {
      username = textBox1.Text;
    }

    // insert password in textfield by user
    private void textBox2_TextChanged(object sender, EventArgs e) {
      password = textBox2.Text;
    }

    // click event after the user clicks `Login`
    private void button1_Click(object sender, EventArgs e) {
      IsValidUser(username, password);
    }

    private bool IsValidUser(string username, string password) {
      bool isValid = false;
      try {
        DirectoryEntry entry = new DirectoryEntry("LDAP://yourdomain.com", username, password);
        object nativeObj = entry.NativeObject;
        isValid = true;
      } catch (DirectoryServicesCOMException comex) {
        // Not Authenticated. comex.Message will return the reason
      } catch (Exception ex) {
        // optional
      }
      return isValid;
    }
  }
}

Use System.DirectoryServices.Protocols Namespace to Validate a User Against Active Directory in C#

Unlike other methods to validate a user against Active Directory, it can differentiate between a password that requires modifications and a user with a wrong password. It will show exceptions if the user password requires change or doesn’t exist.

It uses the lexc.ServerErrorMessage to throw exceptions whose data value is a hex representation of the Win32 Error code. The error codes lexc.ServerErrorMessage contains are the same, which would be returned by otherwise invoking the Win32 LogonUser API call.

The System.DirectoryServices.Protocols namespace in C# provides the methods defined in the LDAP version 3 and DSML version 2.0 standards. With the help of the LdapConnection class, it creates a TCP/IP or UDP LDAP connection to Active Directory to authenticate a user.

Example Code:

using System;
using System.Net;
using System.Windows.Forms;
using System.DirectoryServices.Protocols;

namespace activeDirectoryAuthentication {
  public partial class Form1 : Form {
    string username, password;
    public Form1() {
      InitializeComponent();
    }

    // insert username in textfield by user
    private void textBox1_TextChanged(object sender, EventArgs e) {
      username = textBox1.Text;
    }

    // insert password in textfield by user
    private void textBox2_TextChanged(object sender, EventArgs e) {
      password = textBox2.Text;
    }

    // click event after the user clicks `Login`
    private void button1_Click(object sender, EventArgs e) {
      try {
        LdapConnection adDatabaseCon = new LdapConnection("LDAP://enteryourdomainaddress.com");
        NetworkCredential credential = new NetworkCredential(username, password);
        adDatabaseCon.Credential = credential;
        adDatabaseCon.Bind();
        MessageBox.Show("You are logged in successfully!");
      } catch (LdapException lexc) {
        String error = lexc.ServerErrorMessage;
        // MessageBox.Show(lexc);
      } catch (Exception exc) {
        // MessageBox.Show(exc);
      }
    }
  }
}

Use ActiveDirectoryMembershipProvider.ValidateUser(String, String) Method to Validate a User Against AD in C#

It belongs to the System.Web.Security namespace, and its primary purpose is to verify or validate the specified username and password in the Active Directory. It features two parameters, the first one is the username string, and the other one is the password string which represents the password for the specified user.

This method returns a Boolean as true or false. The true represents a valid user, and the ValidateUser(String, String) method returns false if the user doesn’t exist in the Active Directory.

The Membership class calls this method to validate user credentials against AD, and if it returns false even when the correct credentials are supplied, it also clarifies the reasons. When validating a user, the provider validates the credentials by connecting to the Active Directory using the specified username and password, not the credentials configured in the application’s configuration file.

However, the ActiveDirectoryMembershipProvider instance will connect to the directory using the configured credentials to confirm that a user exists within the search scope and to check it the EnablePasswordReset property is true, and it will use the configured credentials to load the user instance.

Example Code:

using System;
using System.Windows.Forms;
using System.Web.Security;  // moved in System.Web.ApplicationServices

namespace activeDirectoryAuthentication {
  public partial class Form1 : Form {
    string username, password;
    bool publicC;
    public Form1() {
      InitializeComponent();
    }

    // insert username in textfield by user
    private void textBox1_TextChanged(object sender, EventArgs e) {
      username = textBox1.Text;
    }

    // insert password in textfield by user
    private void textBox2_TextChanged(object sender, EventArgs e) {
      password = textBox2.Text;
    }

    // to check if the account is a public account or an admin account
    private void radioButton1_CheckedChanged(object sender, EventArgs e) {
      publicC = radioButton1.Checked;
    }

    // click event after the user clicks `Login`
    private void button1_Click(object sender, EventArgs e) {
      // use `ActiveDirectoryMembershipProvider` as the default membership provider
      var adok = Membership.Provider.ValidateUser(username, password);

      if (Membership.ValidateUser(username, password)) {
        FormsAuthentication.RedirectFromLoginPage(username, publicC);
      } else
        MessageBox.Show("Login failed. Please check your user name and password and try again.");
    }
  }
}

The Active Directory authentication simplifies the sign-in experience for users and reduces the risk of attacks by maximizing security. With the help of Active Directory, you can validate an account immediately by using the user’s updated credentials with on-premises devices and C# applications.

Microsoft’s Active Directory is a critical part of IT infrastructure, and without a proper approach to access, it can put the entire IT environment at risk. In this tutorial, you have learned the optimized ways to validate or authenticate a user/account against Active Directory in C#.

Syed Hassan Sabeeh Kazmi avatar Syed Hassan Sabeeh Kazmi avatar

Hassan is a Software Engineer with a well-developed set of programming skills. He uses his knowledge and writing capabilities to produce interesting-to-read technical articles.

GitHub

Related Article - Csharp Authentication