Thursday, 2 August 2007

ASP.NET - LDAP Domain Information

Ever wanted to retrieve properties of a user from the domain? An easy way is through LDAP (providing the service is running).

Declare the following:

Imports System.DirectoryServices

Now place the following in your code, where appropriate:

Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://SERVER", "USERNAME", "PASSWORD")
Dim osearcher As New DirectorySearcher(oroot)
Dim oresult As SearchResultCollection
Dim result As SearchResult

Dim FINDUSERNAME = "jbloggs"

osearcher.Filter = "(&(objectCategory=person)(sAMAccountName=" & FINDUSERNAME & "))"
osearcher.PropertiesToLoad.Add("cn") ' username
osearcher.PropertiesToLoad.Add("name") ' full name
osearcher.PropertiesToLoad.Add("department") ' department
osearcher.PropertiesToLoad.Add("givenname") ' firstname
osearcher.PropertiesToLoad.Add("sn") ' lastname
osearcher.PropertiesToLoad.Add("mail") ' mail
osearcher.PropertiesToLoad.Add("initials") ' initials
osearcher.PropertiesToLoad.Add("ou") ' organizational unit
osearcher.PropertiesToLoad.Add("userPrincipalName") ' login name
osearcher.PropertiesToLoad.Add("distinguishedName") ' distinguised name
osearcher.PropertiesToLoad.Add("sAMAccountName") 'userlogin

oresult = osearcher.FindAll()

dim username
dim fullname

For Each result In oresult
username = result.GetDirectoryEntry.Properties("cn").Value
fullname = result.GetDirectoryEntry.Properties("name").Value
Response.Write("Error processing details")
End Try

The above example will look up the user jbloggs using the credentials USERNAME and PASSWORD to connect to the server and return the username and fullname, although you can retrieve any one of the properties that are mentioned, such as result.GetDirectoryEntry.Properties("department").Value for that persons department.

No comments: