Check if a user is a member of a specified domain security group using a secure LDAP query with ADsDSoObject provider. Works for ASP and VBScript using a specified domain service/proxy user account (when anonymous LDAP is disabled).
Example:
If IsMemberOf("SalesManagers", "JohnDoe") Then
Response.Write "is a member"
End If
Const ldap_user = "domain\useraccount"
Const ldap_pwd = "P@ssW0rd$"
Const ou = "OU=Sales,OU=North America,OU=Corp,DC=contoso,DC=com"
Const ADS_SCOPE_SUBTREE = 2
Function IsMemberOf(groupName, uid)
Dim objConnection, objCommand, objRecordSet
Dim retval : retval = False
Dim i, gplen : gplen = Len(groupName)+3
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 memberof 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
For each m in objRecordSet.Fields("memberof").value
If Left(Ucase(m),gplen) = Ucase("CN=" & groupname) Then
retval = True
End If
Next
Next
objRecordSet.MoveNext
Loop
objRecordSet.Close
Set objRecordSet = Nothing
Set objCommand = Nothing
Set objConnection = Nothing
IsMemberOf = retval
End Function
No comments:
Post a Comment