Multiple LDAP authentication in Django

Django allows multiple LDAP configuration. The example of the configuration is given here: https://pythonhosted.org/django-auth-ldap/multiconfig.html

To do this we need to create a Python module under site-packages. For example we can create a module called ‘mypackage’.

$ ls /home/administrator/websenv/lib/python2.7/site-packages/mypackage
__init__.py ldap.py

We can leave __init__.py empty, and write the following entry into ldap.py:

#ldap.py
from django_auth_ldap.backend import LDAPBackend

class LDAPBackend1(LDAPBackend):
 settings_prefix="AUTH_LDAP_1_"

class LDAPBackend2(LDAPBackend):
 settings_prefix="AUTH_LDAP_2_"

class LDAPBackend3(LDAPBackend):
 settings_prefix="AUTH_LDAP_3_"

Now, we can configure the ldap in Django settings.py. This is an example of a configuration in Django.

import ldap
from django_auth_ldap.config import LDAPSearch


AUTHENTICATION_BACKENDS = (
    'mypackage.ldap.LDAPBackend1',
    'mypackage.ldap.LDAPBackend2',
    'mypackage.ldap.LDAPBackend3',
    'django.contrib.auth.backends.ModelBackend',
)

AUTH_LDAP_2_SERVER_URI = "ldap://student.myschool.edu.sg"
AUTH_LDAP_3_SERVER_URI = "ldap://stafff.myschool.edu.sg"
AUTH_LDAP_1_SERVER_URI = "ldap://192.168.3.16"

AUTH_LDAP_2_USER_DN_TEMPLATE = "%(user)s@student.myschool.edu.sg"
AUTH_LDAP_3_USER_DN_TEMPLATE = "%(user)s@staff.myschool.edu.sg"
AUTH_LDAP_1_USER_DN_TEMPLATE = "%(user)s@myschool.edu.sg"

AUTH_LDAP_2_BIND_DN = "dc=STUDENT,dc=MYSCHOOL,dc=EDU,dc=SG"
AUTH_LDAP_3_BIND_DN = "dc=STAFF,dc=MYSCHOOL,dc=EDU,dc=SG"
AUTH_LDAP_1_BIND_DN = "dc=MYSCHOOL,dc=EDU,dc=SG"

In the example above, we created three backends LDAP1, 2, and 3. We first import the backends to Django and set the URI, DN_TEMPLATE, and bind the domain.

We may need to restart Django and the server:

$python manage.py syncdb
$sudo apachectl restart
Advertisements

Fixing Django admin style

I was trying out django tutorial. It works fine when I use the webserver provided by django. But when I tried to deploy on an Apache server. The admin page has lost its style. I tried to google around, and show suggestion to set Apache Alias for media to redirect to the media folder for django. But I couldn’t find media folder for django. It turns out that from django 1.4 onwards we should refer to static folder instead. So this is the modification that I made:

On /etc/apache2/apache2.conf:

<pre>

Alias /static/admin /home/ubuntu/websenv/lib/python2.7/site-packages/django/contrib/admin/static/admin/

</pre>

to point to the location of the static files for admin page. And that solves my problem.