pythonpython-3.7ldap3

Python ldap3 how to get all members of a group


I have tried every solution on Stackoverflow for this and none work. Using python3 and ldap3 I can make the bind with the user and with the service account and I can even extract the users email address. But I cannot verify that he is from a certain group. I am trying to get all members of the group and then I will see if he exists in that group.

Users DN: OU=Users,O=Acme Who is a member of: CN=my-users,OU=MyUsers,OU=Groups,O=Acme

Here is the code I have so far..

try:
    l = bind_user(MyServiceAccount, MyServiceAccountPassword)
except Exception as e:
    logger.info(f'Error attempting to bind with ldap server: {e}')
    return(f'Error logging in. Details: {e}')

    #### This first search works and returns the users email address ###
    search_filter = f"(cn={user_name})"
    search_attribute =['mail']
    l.search(search_base='OU=Users,O=Acme',
         search_scope=SUBTREE,
         search_filter=search_filter,
         attributes=search_attribute)

    print('l.response',l.response)
    email = l.response[0]['attributes']['mail'] # All Good to here

    
   
    ### This next search does not work. it just returns and empty list 
    l.search(
        search_base='CN=my-users,OU=MyUsers,OU=Groups,O=Acme',
        search_filter='(cn=my-users)',
        search_scope='SUBTREE',
        attributes = ['member'],
        size_limit=0
    )
    
    print(f'printing entries = {l.entries}') # Outputs []
    print(f'Group response = {l.response}') # This also outputs []
    
    for entry in l.entries: # Never happens
        print(entry.member.values)

Solution

  • If you just need to verify that your user is a member of my-users then you dont need the second search. Instead add the search attribute "memberOf" search_attribute =['mail', 'memberOf'] to your first search and then parse it the same way you did mail. Something like this ..

        user_group_dn = 'CN=my-users,OU=MyUsers,OU=Groups,O=Acme'
        search_filter = f"(cn={user_name})"
        search_attribute =['mail', 'memberOf']
        l.search(search_base='OU=Users,O=Acme',
             search_scope=SUBTREE,
             search_filter=search_filter,
             attributes=search_attribute)
    
        print('l.response',l.response)
        email = l.response[0]['attributes']['mail'] 
        memberOf = l.response[0]['attributes']['memberOf'] #This is the key
        #memberOf should bring back ['CN=my-users,OU=MyUsers,OU=Groups,O=Acme','Someothe user groups']
    
        if user_group_dn in memberOf:
            # do some stuff here. allow login