RSS

djangoでLDAP認証

djangoでLDAP認証する方法

Django's new authentication backends という記事もあるのだが、これではanonymousでできないのでちょっと改良。anonymousでbindしてdnを捜して、そのdnで認証するという手順。手順は普通の話。

import ldap

import ldap
from django.contrib.auth.models import User

# Constants
AUTH_LDAP_SERVER = '192.168.0.1'

class LDAPBackend:
def authenticate(self, username=None, password=None):
base = "ou=Users,dc=example,dc=jp"
scope = ldap.SCOPE_SUBTREE
filter = "(&(objectclass=person) (uid=%s))" % username
ret = ['dn']

# Authenticate the base user so we can search
try:
l = ldap.open(AUTH_LDAP_SERVER)
l.protocol_version = ldap.VERSION3
except ldap.LDAPError:
return None

try:
result_id = l.search(base, scope, filter, ret)
result_type, result_data = l.result(result_id, 0)
# print result_data
if (len(result_data) != 1):
return None

# Attempt to bind to the user's DN
l.simple_bind_s(result_data[0][0],password)


try:
user = User.objects.get(username__exact=username)
except:
# Theoretical backdoor could be input right here. We don't
# want that, so input an unused random password here.
# The reason this is a backdoor is because we create a
# User object for LDAP users so we can get permissions,
# however we -don't- want them able to login without
# going through LDAP with this user. So we effectively
# disable their non-LDAP login ability by setting it to a
# random password that is not given to them. In this way,
# static users that don't go through ldap can still login
# properly, and LDAP users still have a User object.
from random import choice
import string
temp_pass = ""
for i in range(8):
temp_pass = temp_pass + choice(string.letters)
user = User.objects.create_user(username,
username + '@example.jp',temp_pass)
user.is_staff = False
user.save()
# Success.
return user

except ldap.INVALID_CREDENTIALS:
# Name or password were bad. Fail.
return None

def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None

ほんのちょっとだけ変更してあります。