Issue Querying LDAP DirectoryEntry in ASP.NET

Posted by davemackey on Stack Overflow See other posts from Stack Overflow or by davemackey
Published on 2010-04-27T20:36:43Z Indexed on 2010/04/27 20:43 UTC
Read the original article Hit count: 319

I have users login to my application via Active Directory and then pull from their AD information to garner information about that user like so:

Dim ID as FormsIdentity = DirectCast(User.Identity, FormsIdentity)
Dim ticket as FormsAuthenticationTicket = ID.Ticket
Dim adDirectory as New DirectoryEntry("LDAP://DC=my,DC=domain,DC=com")
Dim adTicketID as String = ticket.Name.Substring(0, 5)
Session("people_id") = adDirectory.Children.Find("CN=" & adTicketID).Properties("employeeID").Value
Session("person_name") = adDirectory.Children.Find("CN=" & adTicketID).Properties("displayName").Value

Now, I want to be able to impersonate other users...so that I can "test" the application as them, so I added a textbox and a button to the page and when the button is clicked the text is assigned to a session variable like so:

 Session("impersonate_user") = TextBox1.Text

When the page reloads I check to see if Session("impersonate_user") has a value other than "" and then attempt to query Active Directory using this session variable like so:

If CStr(Session("impersonate_user")) <> "" Then
  Dim adDirectory as New DirectoryEntry(LDAP://DC=my,DC=domain,DC=com")
  Dim adTicketID as String = CStr(Session("impersonate_user"))
  Session("people_id") = adDirectory.Children.Find("CN=" & adTicketID).Properties("employeeID").Value
  Session("person_name")= adDirectory.Children.Find("CN=" & adTicketID).Properties("displayName").Value
Else
  [use the actual ticket.name to get this info.]
End If

But this doesn't work. Instead, it throws an error on the first Session line stating, "DirectoryServicesCOMException was unhandled by user code There is no such object on the server." Why? I know I'm giving it a valid username! Is something strange happening in the casting of the session? The code is essentially the same between each method except that in one method rather than pulling from ticket.Name I pull from a session variable for the login I'll be looking up with AD.

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about ldap