views:

239

answers:

2

We want to use a "proxy user" to connect to an LDAP server (Active Directory, Novell, or otherwise) and then make sure that the user trying to log into the application has typed in an acceptable user name and password. I have got the code for connecting to LDAP just fine, but I'm at a loss as to how to check the user name and password. Can you do this through an LDAP query?

Here's the guts of my code so far:

Public Function Authenticate(ByVal UserName As String, ByVal Password As String)

  Dim LDAPServer As String = ConfigurationManager.AppSettings("LDAPServer")
  Dim proxyUsername As String = ConfigurationManager.AppSettings("LDAPProxyUser")
  Dim proxyPassword As String = ConfigurationManager.AppSettings("LDAPProxyPassword")

  Dim entry As DirectoryEntry

  entry = New DirectoryEntry(LDAPServer, proxyUsername, proxyPassword)

  'This performs the LDAP authentication'
  Dim obj As Object = entry.NativeObject

  Dim search As New DirectorySearcher(entry)
  search.Filter = String.Format("(SAMAccountName={0})", UserName)

  'How do I check the password now?'

  Dim result As SearchResult = search.FindOne()

  If result Is Nothing Then Throw New Exception("Unable to find SAMAccountName")
+1  A: 

The code I've used in the past tries to bind to the LDAP using the provided credentials. If the call to bind throws an exception, then you do not have a valid user:

Dim servers() As String = New String(0) {"mylap.domain.com"}
Dim con As New LdapConnection(New LdapDirectoryIdentifier(servers, True, False))
con.SessionOptions.SecureSocketLayer = True
con.Credential = New Net.NetworkCredential("cn=" & userName, password)
con.AuthType = AuthType.Basic

Using con
   con.Bind()
End Using
Jason Berkan
A: 

I ended up creating another DirectoryEntry which was the user who was trying to authenticate like this:

Dim authEntry As DirectoryEntry

authEntry = New DirectoryEntry(LDAPServer, UserName, Password)

Dim authObj = authEntry.NativeObject

If this throws an exception, the user failed to authenticate.

Brandon Montgomery