Tuesday, July 14, 2009

VBScript / ASP Secure LDAP User Query

Query Active Directory using a service/proxy user account from within VBScript or an ASP web page. Returns results as a tab-delimited string, where each token is sub-delimited using a pipe character "|".


example:
x = GetUserData("JohnDoe", "ADsPath, mail, department, givenName, sn")

For each v in Split(x, vbTab)
response.write Replace(v, "|", " = ") & "<br/>"
Next


Const ldap_user = "domain\useraccount"
Const ldap_pwd = "P@ssW0rd$"
Const ou = "OU=Sales,OU=North America,OU=Corp,DC=contoso,DC=com"

Function GetUserData(uid, fields)
Const ADS_SCOPE_SUBTREE = 2
Dim objConnection, objComment, objRecordSet
Dim retval : retval = ""
Dim i, fieldname, strvalue

On Error Resume Next
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")

objConnection.Provider = "ADsDSOObject"
objConnection.Properties("User ID") = ldap_user
objConnection.Properties("Password") = ldap_pwd
objConnection.Properties("Encrypt Password") = TRUE
objConnection.Properties("ADSI Flag") = 1
objConnection.Open "Active Directory Provider"

Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.CommandText = "SELECT " & fields & _
" FROM 'LDAP://" & ou & "' " & _
"WHERE objectCategory='user' AND sAMAccountName='" & uid & "'"

Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst
Do Until objRecordSet.EOF
For i = 0 to objRecordSet.Fields.Count -1
fieldname = objRecordSet.Fields(i).Name
strvalue = objRecordSet.Fields(i).Value
If retval <> "" Then
retval = retval & vbTab & fieldname & "|" & strValue
Else
retval = fieldname & "|" & strValue
End If
Next
objRecordSet.MoveNext
Loop
GetUserData = retval
End Function

No comments:

Post a Comment