• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1775
  • Last Modified:

Active Directory authentication/group membership check with MSAccess 2007 VBA

I'm unfortunately responsible for maintaining some old interfaces written in VBA through MS Access. Currently I'm migrating these over to a new server and one of the things I want to do is improve the login system for these interfaces by integrating them with Active Directory. It's pretty simple: All I need to do is (a) check to make sure the provided username/password combination are correct, and if so, (b) check to see if the user is in a specific Active Directory group.

Any ideas on how to go about doing this? I had written a library in .NET that these interfaces were using on the old server, but on the new server it's not working properly. If there's some way that I can pretty easily and effectively do it right through VBA, I'd prefer that over having to troubleshoot this library that I wrote.

EDIT: I should add, I've been playing around with ADODB to make the connection. It seems to work and I can look up AD object properties but I'm not sure what the best way is to check the username/password.
  • 5
  • 5
  • 2
2 Solutions
Neil RussellTechnical Development LeadCommented:
OK, here goes......

You best solution is going to be the fact that the user has ALREADY Authenticated againt the domain when they log in.  Therefore all you need to check is if they are a member of the security group that allows access...

Code below is functional but i just hacked it together from several sources with no inline error checking, but it worked.

In access VBA Insert the snippet below into a a new MODULE

Public Declare Function GetUserName Lib "advapi32.dll" _
Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Public Const adOpenStatic     As Integer = 3
Public Const adLockReadOnly   As Integer = 1
Public Const adCmdUnspecified As Integer = -1

' Testing function. Replace "NAME OF GROUP" with a real AD Security group name
Sub TestMe()
    Debug.Print IsUserInGroup("NAME OF A GROUP")
End Sub

' returns the  Domain User Name for the currently logged in user
Function ReturnUserName() As String
    Dim rString As String * 255, sLen As Long, tString As String
    tString = ""
    On Error Resume Next
    sLen = GetUserName(rString, 255)
    sLen = InStr(1, rString, Chr(0))
    If sLen > 0 Then
        tString = Left(rString, sLen - 1)
        tString = rString
    End If
    On Error GoTo 0
    ReturnUserName = UCase(Trim(tString))
End Function

'Test if the current logged in user is a member of a named group
'DOES NOT WORK WITH Primary Group in AD
Public Function IsUserInGroup(groupName As String) As Boolean

    Dim rs, rs2 As Object
    Dim uName As String
    Dim LdapUser As String
    Dim strSQL As String
    Dim i As Integer
    Set rs = CreateObject("ADODB.Recordset")
    strSQL = "SELECT * " & _
             "FROM 'LDAP://DC=xshis,DC=nhs,DC=uk'" & _
             "WHERE objectClass='user' AND objectCategory='Person' AND sAMAccountName ='" & ReturnUserName & "' "

    rs.Open strSQL, "Provider=ADSDSOObject;", adOpenStatic, adLockReadOnly, adCmdUnspecified
    If Not rs.EOF And Not rs.bof Then
            uName = rs.Fields("ADSPath")
            LdapUser = Mid(uName, 8)
            strSQL = "SELECT * " & _
                     "FROM 'LDAP://DC=xshis,DC=nhs,DC=uk'" & _
                     "WHERE objectClass='Group' AND Member = '" & LdapUser & "' "

            Set rs2 = CreateObject("ADODB.Recordset")
            rs2.Open strSQL, "Provider=ADSDSOObject;", adOpenStatic, adLockReadOnly, adCmdUnspecified
            While Not rs2.EOF And Not rs2.bof
                If (InStr(1, rs2.Fields(0).Value, "CN=" & groupName, vbTextCompare) > 0) Then
                    IsUserInGroup = True
                    GoTo exitFunc
                End If
    End If
    IsUserInGroup = False
    'Close connection and tidy up
    Set rs2 = Nothing
    Set rs = Nothing
End Function

Open in new window

And there you are. You can test if a user is in a group.
In addition ... if you wish to protect your data, then place your data in a Shared Folder, then assign an Active Directory group full permissions in to the folder.  All your Front Ends should be local (or private) to the user who has access to the back end.

Also, as an alternative to Neilsr's suggestion, here is what I use to determine the groups the current logged in user is in.  It returns a pipe delimited list of groups the user is in for the passed domain.

Public Function GroupsForCurrentUser(strDomain As String) As String

    Dim sADsPath As String, sGroupName As String _
        , sDescription As String, sUsersGroupList As String
    Dim oTarget As Object
    Dim vGroup As Variant
    Dim wshNetwork As Object
    Set wshNetwork = CreateObject("wscript.network")
    ' Bind to Computer object
    Set oTarget = GetObject("WinNT://" & strDomain & "/" & wshNetwork.UserName & ",user")
    For Each vGroup In oTarget.Groups
        sUsersGroupList = sUsersGroupList & "|" & vGroup.Name
    sUsersGroupList = UCase(sUsersGroupList)
    GroupsForCurrentUser = sUsersGroupList & "|"
End Function

Open in new window

I will use the function like this ...

If GroupsForCurrentUser("someDomain") Like "*|someGroupName|*"  Then ....

Open in new window

elorcAuthor Commented:
Thanks for the replies. For security and auditing purposes, these interfaces are required to authenticate the user again when they are launched before access can be granted. We are not allowed to assume that the user is authenticated because they are logged into Windows already.
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

>>  We are not allowed to assume that the user is authenticated because they are logged into Windows already. <<

Do you mean authenticated to use your app?  or .. Are you not allowed to assume the logged in user is the one in front of the computer?
elorcAuthor Commented:
Whenever they load the interface, it has to prompt them for the password. The assumption is that just because they are logged into Windows does not mean they're the person currently at the keyboard, so the interface must require login credentials every time it's opened.
The code in the module attached to the post found by clicking this link:


Will likely help you out, honestly it was more complex than what I would hope for after doing the same thing in C#, but from a brief read of the code, seems like what you want.  It is likely there are other technics out there, but this one caught my eye.

If this does not work, we can look at some other references I found.
elorcAuthor Commented:
That seems to work. What a cluser though. :)

I've been working on rewriting these crappy interfaces as actual .NET applications, but it's pretty time consuming so it's taking me a while to get them all done. This will keep the ones I haven't gotten to yet limping along for the time being. Thank you.
Neil RussellTechnical Development LeadCommented:
Nice find! :D

Can I suguest you use the first part to find the current logged on username and just prompt for the password? Avoid a user running the app in another users windows session?  I know i would find that insecure somewhere along the line if your concerns are what they are.

Yes it is a cluster! ... so I kept digging -- it was really bothering me! .. and this is what I came up with.  It works for me on my PC in VBA, but I am an administrator, so I don't know if permissions will be an issue.

Public Function ValidateUser(strDomain As String, strUserName As String, strPassword As String) As Boolean
    Dim oADobject As Object 'IADsOpenDSObject
    Set oADobject = GetObject("WinNT:")
    On Error Resume Next
    oADobject.OpenDSObject "WinNT://" & strDomain, strUserName, strPassword, &O1 'ADS_SECURE_AUTHENTICATION)
    ValidateUser = (Err = 0)
End Function

Open in new window

By the way, it seems the code I first linked you to was born out of this MS article ...

elorcAuthor Commented:
That second code you provided works under normal users as well. When the login credentials are incorrect it looks like it can sometimes take several seconds to return false, but that's fine. I like the simplicity of that solution.
Cool! ..

In my testing, I did notice the delay when an error was thrown also.  But, like you, I prefer the simplicity and will take the hit of the small delay versus the hit of a module with code that I would rather not touch!

Either way you go, I am glad the information found helped you out!  I learned some stuff too, so it was a double bonus!

Good luck on your project(s)!
elorcAuthor Commented:
I'll just explain to users that the small delay is "an intentional implementation designed to reduce the effectiveness of brute force attacks."


Thanks again for the assistance that you both provided. I was able to put it all together to do exactly what I was looking for.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

  • 5
  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now