Thursday, December 14, 2023

Retrieve Active Directory Group Membership Info

Hello, everyone! It's been a while since I wrote something here. I hope I can get back into it.

I was helping someone in the forum recently regarding how to check if a user was a member of a certain active directory (AD) group. They wanted to use this information to add some security features to their Access application. In the process of helping them, I ended up creating two functions. The first one is used to create a list of all the AD groups for a given user. The second one is used to verify if a given user is a member of a specified network group. (The forum poster really only needed the second function, but I had to create the first one, so I can properly check the second function.)

ListUserGroups()

As already mentioned, this function will iterate through the group membership for a given username. If the username is not provided, the function will list the group membership for the current user. The sample function below simply outputs the group listing in the Immediate Window. It is up to you to modify the function to store or display the information as required in your project.
Public Function ListUserGroups(Optional User As String) As Boolean
'thedbguy@gmail.com
'12/13/2023

Dim objUser As Object
Dim objGroup As Object
Dim strDomain As String

With CreateObject("WScript.Network")
    strDomain = .UserDomain
    If User = "" Then User = .UserName

End With

Set objUser = GetObject("WinNT://" & strDomain & "/" & User & ",user")

For Each objGroup In objUser.Groups
    Debug.Print objGroup.Name

Next

Set objGroup = Nothing
Set objUser = Nothing

End Function

IsGroupMember()

In contrast, the following function will simply return True or False to verify if the user is a member of a given network group. As I said earlier, I had to create the first function, because I needed to know the correct group name that I can use to check and verify if I was a member of it or not.

Public Function IsGroupMember(GroupName As String, Optional User As String) As Boolean
'thedbguy@gmail.com
'12/13/2023

Dim objGroup As Object
Dim strDomain As String
Dim strDomainUser As String

With CreateObject("WScript.Network")
    strDomain = .UserDomain
    If User = "" Then User = .UserName

End With

strDomain = "WinNT://" & strDomain & "/"

Set objGroup = GetObject(strDomain & GroupName & ",group")

IsGroupMember = objGroup.IsMember(strDomain & User)

Set objGroup = Nothing

End Function

Please note, the above functions do not contain any error handlers. I recommend that you consider adding them when you implement the above functions in your database.

I hope these functions would also come handy in your own Access application projects.