A Mutable Log

Authenticate credentials in C# using LDAP

In this post, we’ll use the C# interactive shell to authenticate a user’s credentials against an LDAP directory service such as Active Directory.

Let’s start by loading the assembly that contains the type we need

#r "System.DirectoryServices.dll"

Next, let’s import the namespace that contains the type

using System.DirectoryServices.AccountManagement;

Next, we create a PricipalContext instance with a domain name

var context = new PrincipalContext(ContextType.Domain, "name");

You can use systeminfo command in the command shell to find the domain name, or in PowerShell, use

echo $env:USERDOMAIN

Next, we call ValidateCredentials with a username and password

var isValid = context.ValidateCredentials("username", "password");

If the username and password combination is valid, the following should print true