How to achieve authentication with django-auth-ldap?

user982809 picture user982809 · Mar 27, 2013 · Viewed 9.3k times · Source

I have an app running using django. Now i want only users that are authenticated via an openldap server to see "their view" (therefore i only need their uid after successfull authentication)

How can i achieve that?

I guess django-auth-ldap is the way to go, so i tried the whole day to get to know where the authentication actually takes place and how i can get the uid of the user requesting a view.

I used the documentation for the settings.py but i could not find out how to "actually use" it. Maybe someone can point me in the right direction?

settings.py:

import ldap

AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

AUTH_LDAP_SERVER_URI = "ldap://123.60.56.61"

AUTH_LDAP_BIND_DN = ""
AUTH_LDAP_BIND_PASSWORD = ""
AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,dc=rd,dc=corpintra,dc=net"

(By the way: i already can perform ldap-searche with python-ldap and get results like ldapsearch on the command line, so everything else works just fine...)

What do i need in my views?

Thanks for your help!

Answer

Thomas picture Thomas · Mar 28, 2013

Here's a snippet from one of our sites.

# Django Auth Ldap
main_dn = 'dc=____,dc=organisation,dc=com'
groups_dn = 'ou=Groups,'+main_dn
users_dn = 'ou=Users,'+main_dn

AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

AUTH_LDAP_SERVER_URI = "ldap://ldap.organisation.com"
AUTH_LDAP_BIND_DN = 'cn=___,'+main_dn
AUTH_LDAP_BIND_PASSWORD = "__________________"
AUTH_LDAP_USER_SEARCH = LDAPSearch(users_dn, 2, "(uid=%(user)s)")
AUTH_LDAP_USER_ATTR_MAP = {
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail"
}
AUTH_LDAP_MIRROR_GROUPS = True
AUTH_LDAP_ALWAYS_UPDATE_USER = True
AUTH_LDAP_GROUP_TYPE = PosixGroupType()
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(groups_dn, ldap.SCOPE_SUBTREE, "(objectClass=posixGroup)")

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    "is_staff":         "cn=admins,"+groups_dn,
    "is_superuser":     "cn=developers,"+groups_dn,
}

EDIT:

Since the question is "What do i need in my views?", The answer is that this config will save the user's uid as the username field on the User model, so in your views, you need

uid = request.user.username

Hopefully this gets you up and running.