LDAP - How to validate a user

In a recent project I had to validate that a user was valid against Active Directory. I'm not that good at LDAP queries so I thought I'd document this code in case it came up again.

The code shows a successful and failed lookup against a domain. Note that there is no password, we're only validating that the user exists.

I'm showing two different approacher, one uses the DirectoryServices namespace and the other uses DirectoryServices.AccountManagement. I'm not expert enough to know which is better... I just need the end result.

 

 

Related Articles

... and you 'll find more on the NET Development Menu

The Active Directory Explorer from SysInternals can help with the parameters

http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx

 


        Dim user As UserPrincipal
        Dim user2 As UserPrincipal
        Try
 
            Dim oPrincipalContext As System.DirectoryServices.AccountManagement.PrincipalContext 
New PrincipalContext(ContextType.Domain, "dyndeveloper.local""CN=Users,DC=dyndeveloper,DC=local")             'locate the user              user = UserPrincipal.FindByIdentity(oPrincipalContext, IdentityType.Name, "Joel")             user2 = UserPrincipal.FindByIdentity(oPrincipalContext, IdentityType.Name, "nobody")         Catch ex As Exception             Dim strError As String = ex.Message         End Try
Second approach:
 
    Function isValidUser() As Boolean
        Dim bResult As Boolean = False
        Dim strUserName As String = Me.txtNetID.Text
        Try
 
            Dim entry As DirectoryEntry = New DirectoryEntry("LDAP://directory.cornell.edu:389/ou=People,o=Cornell University,c=US")
            entry.AuthenticationType = AuthenticationTypes.ServerBind
 
            Dim ds As DirectorySearcher = New DirectorySearcher(entry, "(uid=" & strUserName & ")")
            Dim results As SearchResultCollection = ds.FindAll()
            Debug.Print(results.Count)
 
            For Each result As SearchResult In results
                Dim props As ResultPropertyCollection = result.Properties
                For Each key As String In props.PropertyNames
                    Debug.Print(key + " = ")
                    For Each item As Object In props(key)
                        Debug.Print("   " + item)
                    Next
                Next
 
            Next
 
        Catch ex As Exception
            Me.lblError.Text = ex.Message
        End Try
 
        Return bResult
    End Function
 

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences