Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticating Domain Users with System.DirectoryServices

Given a username and a password for a domain user, what would be the best way to authenticate that user programatically?

like image 699
John Christensen Avatar asked Aug 27 '08 18:08

John Christensen


People also ask

What is System DirectoryServices AccountManagement?

DirectoryServices. AccountManagement) Encapsulates the account data and operations common to all security principals. This is the abstract base class from which all security principals are derived.

What is DirectorySearcher in c# net?

FindAll Method (System. DirectoryServices) Executes the search and returns a collection of the entries that are found.

What is C# DirectoryEntry?

DirectoryEntry(String) Initializes a new instance of the DirectoryEntry class that binds this instance to the node in Active Directory Domain Services located at the specified path. DirectoryEntry(String, String, String) Initializes a new instance of the DirectoryEntry class.

What is C# PrincipalContext?

PrincipalContext(ContextType, String, String, ContextOptions) Initializes a new instance of the PrincipalContext class with the specified context type, name, container, and context options.


2 Answers

It appears that .NET 3.5 added a new namespace to deal with this issue - System.DirectoryServices.AccountManagement. Code sample is below:

Private Function ValidateExternalUser(ByVal username As String, ByVal password As String) As Boolean
    Using context As PrincipalContext = New PrincipalContext(ContextType.Domain, _defaultDomain)
        Return context.ValidateCredentials(username, password, ContextOptions.Negotiate)
    End Using
End Function

The namespace also seems to provide a lot of methods for manipulating a domain account (changing passwords, expiring passwords, etc).

like image 54
John Christensen Avatar answered Sep 22 '22 15:09

John Christensen


You can use some hacks to authenticate only.

Try
    Dim directoryEntry as New DirectoryEntry("LDAP://DomainController:389/dc=domain,dc=suffix", "username", "password")
    Dim temp as Object = directoryEntry.NativeObject
    return true
Catch
    return false
End Try

If the user is not valid, the directory entry NativeObject cannot be accessed and throws an exception. While this isn't the most efficient way (exceptions are evil, blah blah blah), it's quick and painless. This also has the super-cool advantage of working with all LDAP servers, not just AD.

like image 38
David J. Sokol Avatar answered Sep 19 '22 15:09

David J. Sokol