Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


LDAP Code to get Active Directory Groups

Posted on 2004-09-20
Medium Priority
Last Modified: 2012-05-05
Can someone please supply me with code to get the groups a member belongs to using ASP and active directory (LDAP)?

I have all sorts of code samples to try to get the active directory groups using ASP (not .Net!) but I can’t get any of them to work. They work fine until I try to get the info on a specific user.

When I try:
strAction = “LDAP://CN=fred,CN=users,DC=domain,DC=local”
Set oContainer = GetObject(strAction)

I get:
Error Type:
/GHACapEx/Common/Security.asp, line 87

Which is not very helpful at all. (Like 87 is the GetObject)

Will pay up to 500 points for brilliant solutions but any help would be greatly appreciated.

Question by:slamhound
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
LVL 11

Expert Comment

ID: 12110015
You most probably just entering the path wrong.

Go and find you Win 2000 support tools and look for a program called ADSI Edit.. it's brilliant for working out this stuff.

You can browse Model to what you want and show you the string that is required to access that object

heres some info to on the prog

and with your example above -- it's an invalid object  it's probably going to be

fred will not be the logon code it will be the name of the object in active directory.

Cheers have fun .. it's not the easist thing to get you head around but the ADSI Edit has save me confusion a million times.

Expert Comment

ID: 12112312

I am not sure where I got this code but it will allow for me to find out what groups a user has and what users a group has.  We are using Active Directory.  The only thing you should have to change is the kearney-ne to your domain.  It also includes a sort function that I got from this list a while back.

Good luck,

Here is my page:

<%@ Language=VBScript %>
<form action method="post" id="form1" name="form1">
Dim x(500,2)

If Len(Request.Form("userid"))AND Request.Form("userid")<> "blank" Then
End If
If Len(Request.Form("group")) Then
End If
Sub getGroups(userID)
    Dim strQuery, strDesc, intI
     strQuery = "WinNT://kearney-ne/" & userID & ",User"
    on error resume next
    Set UserObj = GetObject(strQuery)
    If userObj Then
         strDesc = userObj.Description
         strDesc = "Not Found"
    End If
    Response.Write "<tr><td><br></td></tr>"
    Response.Write "<tr class=header><td colspan=2>NT Groups for " & userID & "&nbsp-&nbsp" & strDesc & "</td></tr>"
    Response.Write "<tr class=subheader><td>Group Name</td><td>Group Description</td></tr>"
    For Each GroupObj In UserObj.Groups
         x(intI,0) = GroupObj.Name
         x(intI,1) = GroupObj.Description
         intI = intI + 1
    Call Quicksort(x,0,intI-1,0)
    Call PrintArray(x,0,intI-1)
    Set UserObj = nothing
End Sub
Sub getUsers(group)
    Dim strQuery, strDesc, intI
    strQuery = "WinNT://kearney-ne/" & group & ",group"
    on error resume next
    Set GroupObj = GetObject(strQuery)
    If GroupObj Then
         strDesc = GroupObj.Description
         strDesc = "Not Found"
    End If
    Response.Write "<tr><td><br></td></tr>"
    Response.Write "<tr class=header><td colspan=2>Users in NT Group " & group & "&nbsp-&nbsp" & strDesc & "</td></tr>"
    Response.Write "<tr class=subheader><td>User ID</td><td>Description</td></tr>"
    For Each UserObj In GroupObj.Members
         x(intI,0) = UserObj.Name
         x(intI,1) = UserObj.Description
         IntI = IntI + 1
    Call Quicksort(x,0,intI-1,0)
    Call PrintArray(x,0,intI-1)

    Set GroupObj = nothing
End Sub
Sub writeForm()
    Response.Write "<tr class=header><td colspan=2>Enter an YourNTDomain User ID OR Group</td></tr>"
    Response.Write "<tr class=subheader><td>User Id:</td><td><input id=userid, name=userid></input>(ie L123456)</td></tr>"
    Response.Write "<tr class=subheader><td><tc>Group:</td><td><input id=group, name=group></input>(ie USA-BUDW)</td></tr>"
    Response.Write "<tr><td><INPUT type=""submit"" value=""Submit"" id=submit1 name=submit1></td></tr>"
End Sub

Sub PrintArray(vec,lo,hi)
  '== Print out an array from the lo bound    ==
  '==  to the hi bound.  Highlight the column ==
  '==  whose number matches parm mark         ==

  Dim i,j
'  Response.Write "<table border=""1"" cellspacing=""0"">"
  For i = lo to hi
    If vec(i,0) <> "" then
      Response.Write "<tr>"
      For j = 0 to Ubound(vec,2)
        Response.Write "<td>" & vec(i,j) & "</td>"  
      Response.Write "</tr>"
    End If
'  Response.Write "</table>"
End Sub  'PrintArray

Sub SwapRows(ary,row1,row2)
  '== This proc swaps two rows of an array
  Dim x,tempvar
  For x = 0 to Ubound(ary,2)
    tempvar = ary(row1,x)    
    ary(row1,x) = ary(row2,x)
    ary(row2,x) = tempvar
End Sub  'SwapRows

Sub QuickSort(vec,loBound,hiBound,SortField)

  '== Sort a 2 dimensional array on SortField                ==
  '==                                                        ==
  '== This procedure is adapted from the algorithm given in: ==
  '==    ~ Data Abstractions & Structures using C++ by ~     ==
  '==    ~ Mark Headington and David Riley, pg. 586    ~     ==
  '== Quicksort is the fastest array sorting routine for     ==
  '== unordered arrays.  Its big O is  n log n               ==
  '==                                                        ==
  '== Parameters:                                            ==
  '== vec       - array to be sorted                         ==
  '== SortField - The field to sort on (2nd dimension value) ==
  '== loBound and hiBound are simply the upper and lower     ==
  '==   bounds of the array's 1st dimension.  It's probably  ==
  '==   easiest to use the LBound and UBound functions to    ==
  '==   set these.                                           ==

  Dim pivot(),loSwap,hiSwap,temp,counter
  Redim pivot (Ubound(vec,2))

  '== Two items to sort
  if hiBound - loBound = 1 then
    if vec(loBound,SortField) > vec(hiBound,SortField) then Call SwapRows(vec,hiBound,loBound)
  End If

  '== Three or more items to sort
  For counter = 0 to Ubound(vec,2)
    pivot(counter) = vec(int((loBound + hiBound) / 2),counter)
    vec(int((loBound + hiBound) / 2),counter) = vec(loBound,counter)
    vec(loBound,counter) = pivot(counter)

  loSwap = loBound + 1
  hiSwap = hiBound
    '== Find the right loSwap
    while loSwap < hiSwap and vec(loSwap,SortField) <= pivot(SortField)
      loSwap = loSwap + 1
    '== Find the right hiSwap
    while vec(hiSwap,SortField) > pivot(SortField)
      hiSwap = hiSwap - 1
    '== Swap values if loSwap is less then hiSwap
    if loSwap < hiSwap then Call SwapRows(vec,loSwap,hiSwap)

  loop while loSwap < hiSwap
  For counter = 0 to Ubound(vec,2)
    vec(loBound,counter) = vec(hiSwap,counter)
    vec(hiSwap,counter) = pivot(counter)
  '== Recursively call function .. the beauty of Quicksort
    '== 2 or more items in first section
    if loBound < (hiSwap - 1) then Call QuickSort(vec,loBound,hiSwap-1,SortField)
    '== 2 or more items in second section
    if hiSwap + 1 < hibound then Call QuickSort(vec,hiSwap+1,hiBound,SortField)

End Sub  'QuickSort
LVL 10

Author Comment

ID: 12119570
Good code, BubbaisBest, but it doesn't seem to require a password. I want users to be able to login (username and password) without stealing someone elses ID (username only).

Thanks, coopzz, but changing the LDAP string as you suggested results in the same error.

Any more ideas?
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

LVL 10

Author Comment

ID: 12119648
Coopzz, the ADSI Edit worked well enough to get group names for a user!!!

But what LDAP value do I have to look at to check that a username and password is correct before I check their groups?

LVL 11

Expert Comment

ID: 12119781
As far as I know you can't check passwords, you can only reset them, so if your trying to check there login in corectly you assign the asp page to win authenication through iis which brings up a win login box.

So if they login in successfully they will hit the asp page and you can look at the Request.ServerVariables("LOGON_USER") to grab there login code and off you go. you can get them to do this automatically if you need to. check out the thread below where I've described it before.

there trying to do the same thing.

LVL 10

Author Comment

ID: 12119924
One of the major issues I had earlier on is that LDAP is looking for an account name ("Selwyn Young") while I was supplying my login name ("Selwyn") and it couldn't find it. The Request.ServerVariables("LOGON_USER") provides a login name. How do I find this account using LDAP?

LVL 11

Accepted Solution

coopzz earned 2000 total points
ID: 12120019
I found this with a simular thing and I modded on of the posts to fit vb.
zcolton (IS/IT--Manageme) was the name to the person.

I tried this in vb6 and it worked fine so you'll have to fine tune it to your own..

Private Sub Command2_Click()
' trying to get the name of the user from sAMAccountName
    dim m_cOrganUnit as string: m_cOrganUnit = "ou=IT,ou=My Business Name"
    Dim objRoot As Object:      Set objRoot = GetObject("LDAP://RootDSE")
    Dim sDomainPath As String:  sDomainPath = objRoot.Get("DefaultNamingContext")
    Dim rs As ADODB.Recordset
    Dim con As ADODB.Connection: Set con = New ADODB.Connection
    con.provider = "ADsDSOObject"
    con.open "Active Directory Provider"
    Dim Com As ADODB.Command:  Set Com = New ADODB.Command
    Set Com.ActiveConnection = con
    Com.CommandText = "select name, sAMAccountname from 'LDAP://" & m_cOrganUnit & "," & sDomainPath & "' WHERE objectCategory='person' AND sAMAccountname='fredG' ORDER BY name"
    Set rs = Com.Execute
    MsgBox rs.Fields("name")
End Sub
LVL 10

Author Comment

ID: 12129538
Thanks Coopzz. We're almost there.

I can't get this code working because I have a different AD structure (I think). I get an EOF if I leave the WHERE clause in and I get "No such table" if I leave the "ou=IT" in. Using ADSIEdit I can find the ou of "MyBusiness" but can find no sAMAccountname property under any list.

Where should i look to find this value?

LVL 11

Expert Comment

ID: 12130125
sorry the sAMAccount is one of the LogonCode Propertys to get or test against (you'll have to look it up but there are 2 one for Ol' NT4 clients and then the other for the 2k above.

m_cOrganUnit  = "ou=IT,ou=My Business Name" was something specific to where I work you have to change this meet your needs.

If you don't know much about active directory you may need to talk to your administrator but bascally where I work we have a ou (Organisation Until) thats our business name and another one under it call IT or Admin or Guests, etc..  so you would have to define your paths acordingly.
 Just Use you ADSI edit to find where The users your looking for and grab the path.  I haven't messed around with recordset approach before but it appears to be so much more powerful than what I looked at before..


heres some of the attributes you can get.

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I would like to start this tip/trick by saying Thank You, to all who said that this could not be done, as it forced me to make sure that it could be accomplished. :) To start, I want to make sure everyone understands the importance of utilizing p…
This demonstration started out as a follow up to some recently posted questions on the subject of logging in: http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28634665.html and http://www.experts-exchange.com/Programming/…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …

609 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question