進行身份驗證我正在使用php將一個網站遷移到Django框架。無法通過自定義PASSWORD_HASHERS
有用於特定的哈希密碼算法,所以我不得不寫:
#settings.py
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'project.hashers.SHA1ProjPasswordHasher', # that's mine
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
...
)
和:
#hashers.py
import hashlib
from django.contrib.auth.hashers import (BasePasswordHasher, mask_hash)
from django.utils.datastructures import SortedDict
from django.utils.encoding import force_bytes
from django.utils.crypto import constant_time_compare
from django.utils.translation import ugettext_noop as _
class SHA1ProjPasswordHasher(BasePasswordHasher):
"""
Special snowflake algorithm from the first version.
php code: $pass=substr(sha1(trim($_POST['password'])),0,8);
"""
algorithm = "unsalted_and_trimmed_sha1"
def salt(self):
return ''
def encode(self, password, salt):
return hashlib.sha1(force_bytes(salt + password)).hexdigest()[:8]
def verify(self, password, encoded):
encoded_2 = self.encode(password, '')
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
return SortedDict([
(_('algorithm'), self.algorithm),
(_('hash'), mask_hash(encoded, show=3)),
])
它的效果很好,當PBKDF2PasswordHasher
是第一:
>>> from django.contrib.auth import authenticate
>>> u = authenticate(username='root', password='test')
>>> u.password
u'pbkdf2_sha256$10000$EX8BcgPFjygx$HvB6NmZ7uX1rWOOPbHRKd8GLYD3cAsQtlprXUq1KGMk='
>>> exit()
然後我把我的SHA1ProjPasswordHasher
放在第一位,首先驗證很好。散列已更改:
>>> from django.contrib.auth import authenticate
>>> u = authenticate(username='root', password='test')
>>> u.password
'a94a8fe5'
>>> exit()
第二次身份驗證失敗。無法使用新的散列進行身份驗證。
>>> from django.contrib.auth import authenticate
>>> u = authenticate(username='root', password='test')
>>> u.password
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'password'
可能是什麼問題?謝謝。
更新:好的,問題變得更加清晰。當我從這裏取出切片:
return hashlib.sha1(force_bytes(salt + password)).hexdigest()[:8]
一切工作正常。我不知道爲什麼..
danihp謝謝,但我找不到驗證和自定義pasword哈希器的問題在那個線程中。 我認爲,自定義口令散列器應該透明地與認證一起工作,而不需要自定義認證。 所以,我認爲這個問題在我的代碼中。 – vlad
您能否重複相同的操作,但在進行身份驗證之前和之後執行'打印u.password'? –
已在帖子中添加。 – vlad