1. 安装包
pip install python-ldap
pip install django-auth-ldap
2. 测试是否安装成功
在python命令行中运行下面命令,无报错正常。
from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion, GroupOfNamesType
3. Django中配置
在项目中的settings.py配置文件中配置LDAP
import ldap
from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion, GroupOfNamesType
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
basedn = "dc=daodao,dc=com"
AUTH_LDAP_SERVER_URI = 'ldap://IP:PORT'
AUTH_LDAP_BIND_DN = ""
AUTH_LDAP_BIND_PASSWORD = ""
AUTH_LDAP_USER_SEARCH = LDAPSearch('dc=XXXXXX,dc=com', ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}
AUTH_LDAP_ALWAYS_UPDATE_USER = True
4. 使用
在login的view中做认证。
def login(request):
if request.session.get('is_login', None):
return redirect("/index/")
if request.method == "POST":
login_form = UserForm(request.POST)
message = "Please Check!"
if login_form.is_valid():
username = login_form.cleaned_data['username']
password = login_form.cleaned_data['password']
try:
user = authenticate(username=username, password=password)
if user is not None:
request.session['is_login'] = True
request.session['user_id'] = user.id
request.session['user_name'] = username
return redirect('/index/')
else:
message = "Password not correct!"
except Exception as e:
logger.error(e)
message = "User not exist."
return render(request, 'login/login.html', locals())
login_form = UserForm()
return render(request, 'login/login.html', locals())