avramov
avramov

Reputation: 2114

Setting up LDAP for Django authentication

I am working on a Django-based intranet app which needs users to authenticate against Active Directory. I've found django-auth-ldap, but I still have absolutely no idea what to do in order to setup a local LDAP server which I could develop against.

I installed AD LDS, but it needed a domain controller, and some SO answers that I read told me that I can't setup that on Windows 7. So I decided to try OpenLDAP instead, and it looks like it's working, but the tutorials I read weren't particularly clear on how the hell do I add data to it?

Would anyone please explain to me what steps do I need to take in order to add and successfully authenticate a Django user profile against a locally running LDAP service, be it OpenLDAP or Active Directory (I'll need to know how to successfully set up the later, if that's at all possible)?

Upvotes: 1

Views: 1419

Answers (1)

BSAFH
BSAFH

Reputation: 745

You may have already solved this by now but just in case:

You need to setup your LDAP repository (done). You need to create some user objects which can bind. This is accomplished by using an LDIF file or a similar method. A very useful tool for visualising your LDAP db is 'Apache Directory Studio'. An example of how an ldif may appear:

dn:cn=myuser,cn=localhost
changetype: modify
add: cn=myuser
userPassword: password01

It will vary depending on your schema. I highly recommend you read the Django docs for implementation specific to you: https://pythonhosted.org/django-auth-ldap/

This is a good example (from the docs):

import ldap
from django_auth_ldap.config import LDAPSearch

AUTH_LDAP_BIND_DN = ""
AUTH_LDAP_BIND_PASSWORD = ""
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",
ldap.SCOPE_SUBTREE, "(uid=%(user)s)")

but assuming you had added a user via ldif to "cn=localhost" then thats the dn you'd use in the search field. As the docs note, you can search the whole directory if you prefer.

If its not clear what is happening:

  1. Import Ldap Module
  2. Import LDAPSEARCH function? from the django module
  3. Set a blank bind DN (this is like a fully qualified username. e.g. uid=myuser,dc=com)
  4. Set a blank bind password
  5. Perform the search. Format like so: ("base",scope,searchfilter)

You can test using the standard ldap module in python:

import ldap
ld = ldap.initialize("ldaps://acme.com:636")
ld.bind_s("userDN","Password")
ld.search_s("cn=acme.com",ldap.SCOPE_SUBTREE,"uid=myuser")

Not really important, but "ldap.SCOPE_SUBTREE", "ldap.SCOPE_BASE" etc are just integers. So you can pass in 0, 1, 2 instead.

Good luck, even if you solved this long ago.

Upvotes: 1

Related Questions