前言
django-auth-ldap能夠?yàn)镈jango提供LDAP登錄支持。只需要少量配置地回,無(wú)需改變Django的認(rèn)證邏輯。對(duì)已有項(xiàng)目侵入性很小俊鱼,使用起來(lái)非常方便刻像。
本篇為大家?guī)?lái)使用django-auth-ldap的安裝和使用方式。
環(huán)境依賴(lài)安裝
環(huán)境信息:
- Fedora 40
- Python 3.12.7
在Linux系統(tǒng)安裝如下依賴(lài):
- gcc
- python-devel
- openldap-devel
然后創(chuàng)建Python虛擬環(huán)境和初始化Django項(xiàng)目:
python -m venv django-demo-project
cd django-demo-project
source bin/activate
pip install Django -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install django-auth-ldap -i https://pypi.tuna.tsinghua.edu.cn/simple/
django-admin startproject mysite
Django-auth-ldap配置
修改項(xiàng)目的settings.py
并闲,增加:
AUTHENTICATION_BACKENDS = ["django_auth_ldap.backend.LDAPBackend"]
然后增加LDAP相關(guān)配置:
import ldap
from django_auth_ldap.config import LDAPSearch
# LDAP服務(wù)地址
AUTH_LDAP_SERVER_URI = "ldap://ldap_ip:389"
# LDAP bind dn和密碼
AUTH_LDAP_BIND_DN = "cn=manager,dc=paultech,dc=com"
AUTH_LDAP_BIND_PASSWORD = "123456"
# 告訴Django如何根據(jù)用戶(hù)名找到用戶(hù)的DN
AUTH_LDAP_USER_SEARCH = LDAPSearch(
"dc=paultech,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
)
編寫(xiě)演示頁(yè)面绎速。新建views.py
增加如下內(nèi)容:
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
def index(request):
username = request.GET["username"]
password = request.GET["password"]
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return HttpResponse("Hello, world. You're logged in.")
else:
return HttpResponse(f"Login failed. Username: {username}, password: {password}")
然后修改urls.py
:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('demo/', views.index, name="demo")
]
到此為止LDAP已經(jīng)配置完畢。接著開(kāi)始驗(yàn)證前面的配置是否正確焙蚓。使用如下命令啟動(dòng)Django server:
cd manage.py所在路徑
python manage.py runserver 0.0.0.0:8080
然后瀏覽器地址欄輸入如下URL:
http://ip:8080/demo/?username=admin&password=correctPassword
其中username和password為正確的密碼∪鞅Γ可以看到瀏覽器返回Hello, world. You're logged in.
购公。說(shuō)明用戶(hù)成功登錄。
接下來(lái)試驗(yàn)登錄失敗的場(chǎng)景雁歌。瀏覽器輸入http://ip:8080/demo/?username=admin&password=wrongPassword
瀏覽器返回Login failed. Username: admin, password: wrongPassword
宏浩,登錄失敗。
自定義LDAPBackend
我們可以通過(guò)繼承框架提供的LDAPBackend類(lèi)靠瞎,重寫(xiě)其authenticate_ldap_user
方法比庄,實(shí)現(xiàn)自定義的認(rèn)證邏輯。
例如我們存入LDAP服務(wù)中的用戶(hù)密碼使用plain text乏盐,在保存之前使用了base64處理佳窑。在Django中為了能夠正常登錄,需要在登錄之前父能,將用戶(hù)輸入的password同樣使用base64處理才行神凑。示例代碼如下:
from django_auth_ldap.backend import LDAPBackend
import base64
class CustomLDAPBackend(LDAPBackend):
def authenticate_ldap_user(self, ldap_user, password):
base64password = base64.b64encode(password.encode("utf-8")).decode("utf-8")
user = ldap_user.authenticate(base64password)
return user
然后修改settings.py
中的AUTHENTICATION_BACKENDS
為我們自定義的LDAPBackend,例如:
AUTHENTICATION_BACKENDS = ["mysite.custom_ldap_backend.CustomLDAPBackend"]
即可生效。
參考文獻(xiàn)
https://django-auth-ldap.readthedocs.io/en/latest/install.html
https://django-auth-ldap.readthedocs.io/en/latest/custombehavior.html