Skip to content
This repository has been archived by the owner on Jun 30, 2021. It is now read-only.

Commit

Permalink
ldap auth supported
Browse files Browse the repository at this point in the history
  • Loading branch information
ichuan committed Apr 18, 2012
1 parent 4535722 commit d004118
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
43 changes: 43 additions & 0 deletions ldap_backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/bin/env python
# coding: utf-8
# yc@2012/04/18

import os, sys, ldap
from django.conf import settings
from django.contrib.auth.models import User

class LDAPBackend(object):
'''
LDAP auth backend
'''

def authenticate(self, username=None, password=None):
if ldap_auth(username, password):
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
user = User(username=username, password='fake pass')
user.is_staff = True
user.save()
return user

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

def ldap_auth(username, password):
if username and password:
bind_dn = settings.LDAP_USER_DN_TEMPLATE % username
bind_password = password
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
ldapobject = ldap.initialize(settings.LDAP_SERVER_URI)
try:
ldapobject.simple_bind_s(bind_dn, bind_password)
return True
except:
return False
finally:
ldapobject.unbind()
return False
9 changes: 9 additions & 0 deletions local_settings.default.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,12 @@
# 如果需要关闭验证码功能,请将下面两个变量置空
CAPTCHA_PUBLIC_KEY = 'CAPTCHA_PUBLIC_KEY'
CAPTCHA_PRIVATE_KEY = 'CAPTCHA_PRIVATE_KEY'

# LDAP 认证需要设置的参数;开启 LDAP 认证需要取消 AUTHENTICATION_BACKENDS 中的注释
# ubuntu 下需要 apt-get install libldap2-dev libsasl2-dev,然后安装 python-ldap
LDAP_SERVER_URI = 'ldap://ldap.test.com'
LDAP_USER_DN_TEMPLATE = 'uid=%s,ou=users,dc=example,dc=com'
AUTHENTICATION_BACKENDS = (
#'ldap_backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)

0 comments on commit d004118

Please sign in to comment.