I searched the web high and low for Active Directory authentication using VB.NET, and all of the articles I found used the impersonate model to do LDAP queries. However, using the System.DirectoryServices.dll library, there’s a simple function that does all of the work for you. This function basically takes a username and password, and tries to authenticate it on the given LDAP (Active Directory).
Instead of writing 20-30 lines of inefficient code, I wanted to make something very short and simple. All this function does is attempt to create an LDAP object using the given credentials. If it fails, then the username/password combination is invalid.
First off, you need to make sure to reference the System.DirectoryServices.dll. Then, include the library in your page, using:
You can use this function along with forms based authentication or just to check a user’s credentials. It takes the following input variables:
path: An LDAP path for the FQDN of your AD. E.g., LDAP://mydomain.com.
user: The user’s account name. Can be prefixed by the domain; e.g., mydomain\tom or just tom.
pass: The user’s password.
Function AuthenticateUser(path as String, user As String, pass As String) As Boolean Dim de As New DirectoryEntry(path, user, pass, AuthenticationTypes.Secure) Try 'run a search using those credentials. 'If it returns anything, then you're authenticated Dim ds As DirectorySearcher = New DirectorySearcher(de) ds.FindOne() Return True Catch 'otherwise, it will crash out so return false Return False End Try End Function
The function returns a simple
False if it successfully binds to the LDAP using the given credentials.
***Update*** I added the
AuthenticationType.Secure to enable the Kerberos/NTLM encryption of the data as it’s passed along the network. I also changed the function to actually search for an object instead of just using the
NativeObject binding. With the updated code, I’ve verified that no clear text is passed (using Network Monitor) and it also works with passwords using symbols.