Search code examples
python-2.7ldappython-ldap

LDAP and AD - are we always allowed to search?


I am developing a django app as a third party for a client, and I need to use LDAP for authentication - I have been assuming that an industry LDAP server will not let just any client search the tree for a DN, so I think I need to construct the DN myself OR somehow authenticate the search, which I can't find documentation for anyplace online.

Client has two different types of consumers for my app - and they are located in separate OU.

My question is: am I being stupid? do I need to worry about authenticating the search? What is the standard way of getting the DN for the user from the username they give when logging in?

Thanks!


Solution

  • It depends on your LDAP implementation.

    Active Directory for example, will not allow unauthenticated searches. In this case you have to first login as an authenticated user, then search the tree.

    For other implementations they might allow anonymous binds.

    Once you are able to search the tree - then its just a matter of writing the correct query. In Active Directory, the login name is stored as sAMAccountName, so to fetch a user you take their login and bind it to the search; however you must authenticate first. Here is some code that does that (without any error checking):

    def get_user(user):
        user_dn = "DC=DEPARTMENT,DC=FOO,DC=COM"
        login_attr = '({}={})'.format('sAMAccountName', user)
    
        conn = ldap.initialize(your_ldap_url)
    
        # The next two lines are required for AD specific
        # quirks, you may have to comment them for other LDAP servers
        conn.set_option(ldap.OPT_REFERRALS, 0)
        conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
    
        conn.bind("Foo User", "Sekret") # Authenticate first
                                        # before searching
        result = conn.search_s(user_dn,
                               ldap.SCOPE_SUBTREE,
                               login_attr)
        return result[0][1]