djangoldappython-ldap

Pattern matching in LDAP Distinguished Name Template


I am trying to authenticate users using django_auth_ldap. I have users in 2 different groups (say= Theta & Gamma, Alpha & Rho),

Currently, to search users I have created 2 authentication backends & mapped USER_DN_TEMPLATE like this:

'CN=%(user)s,OU=Television,OU=Theta,OU=Gamma,DC=example,DC=com'

to first backend & like this :

'CN=%(user)s,OU=Television,OU=Alpha,OU=Rho,DC=example,DC=com'

to the second backend.

All my other settings are same. I know, this is not ideal setup but I want to know what should my DN_TEMPLATE look like if I need to find all users in one authentication backend only?

There should be some REGEX like pattern to replace Theta/Gamma/Alpha/Rho & then it should work (similar to %(user)s in above patterns.

The other approach will be to set some SCOPE_SUBTREE (& other variables) so that, it searches all users in 'DC=example,DC=com'. I need help on those variables & values.


Solution

  • You need to leave AUTH_LDAP_USER_DN_TEMPLATE unset, and set AUTH_LDAP_USER_SEARCH instead.

    The search/bind authentication method involves connecting to the LDAP server either anonymously or with a fixed account and searching for the distinguished name of the authenticating user. Then we can attempt to bind again with the user’s password.

    For example, you can set the base search to a relative dn that is common to all users :

    AUTH_LDAP_USER_SEARCH = LDAPSearch(
        "DC=example,DC=com", ldap.SCOPE_SUBTREE, "(CN=%(user)s)"
    )
    

    Or you can narrow the search by using multiple bases (search unions) :

    AUTH_LDAP_USER_SEARCH = LDAPSearchUnion(
        LDAPSearch("OU=Television,OU=Theta,OU=Gamma,DC=example,DC=com", ldap.SCOPE_SUBTREE, "(CN=%(user)s)"),
        LDAPSearch("OU=Television,OU=Alpha,OU=Rho,DC=example,DC=com", ldap.SCOPE_SUBTREE, "(CN=%(user)s)"),
    )
    

    If you set AUTH_LDAP_USER_DN_TEMPLATE, django_auth_ldap will skip the search phase and proceed to a direct bind by deriving the user’s DN from his username and attempt to bind as the user directly.

    As the DN template only allows one placeholder for the username, you can use the direct bind method only if all users have their entries in the same container.