[英]Using Django authentication system with existing hashed passwords
我有一個帶有用戶表的非常老的Perl CGI系統。 使用crypt
函數將密碼存儲為計算得出的哈希值。 我希望將系統遷移到Django,並且我想在使用Django表結構時保留用戶數據。
一種選擇是將所有用戶/密碼數據復制到auth_user
表中,並使用自定義身份驗證功能,因為我已有密碼哈希。
我有更好的選擇嗎?
如果我選擇此選項,那么如何實現呢?
編寫自定義身份驗證后端的文檔在Django中的自定義身份驗證中
由於Borodin提出了要求,並且由於您可能會發現有一個更具體針對您的請求的示例很方便,因此我繼續寫了一個示例,該示例針對基於crypt
的文件(例如htpasswd
)進行身份驗證。
如果后端在crypt
文件中找到密碼匹配的用戶,則它將尋找標准的Django用戶並返回。 如果找不到,它將創建一個。 顯然,您需要決定如何處理實現的實際細節。
import crypt
from django.conf import settings
from django.contrib.auth.models import User
class CryptBackend(object):
def authenticate(self, request, username=None, password=None):
crypt_file = getattr(settings, "CRYPT_DB", None)
if crypt_file is None:
return None
password_match = False
with open(crypt_file,"r") as f:
for line in f:
(user, crypted_pass) = line.rstrip().split(":")
if user == username:
password_match = crypt.crypt(password, crypted_pass) == crypted_pass
break
if not password_match:
return None
# found a match in our crypt database
try:
django_user = User.objects.get(username=username)
except User.DoesNotExist:
django_user = User.objects.create_user(username=username, email='', password=password)
django_user.is_staff = True
django_user.save()
return django_user
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
該新的自定義后端將根據settings.py
添加內容進行加載。 在我的示例中,我保留了默認的Django后端,並僅添加了新的自定義后端。 Django會按順序檢查它們,因此它將嘗試標准的Django身份驗證,如果不起作用,請轉到我的自定義身份驗證。 CRYPT_DB
參數是htpasswd
文件的路徑。
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'authbackend.CryptBackend',
]
CRYPT_DB = '/path/to/your/passwd.file'
為了完整htpasswd
,上面要檢查的格式( htpasswd
)的示例。
jill:C.1oP2DOot4MY
jack:qJn7lPS/VNssM
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.