Django User.check_password 无法通过密码检查
Django User.check_password wouldn't pass password check
正在尝试编写一个单元测试来检查用户是否输入了正确的密码。
为此使用 Django 的本机身份验证功能 user.check_password
。
问题是 check_password
出于某种原因不接受 user
对象自己的密码。例如,这会引发错误:
assert user.check_password(user.password), "Password doesn't match"
user.password
returns MD5 unicode 字符串。
有谁知道为什么这个检查不通过,怎么才能通过检查?
发生这种情况是因为 check_password
接受原始字符串并且您正在向它传递哈希值。
assert user.check_password(user.password) # False because passing hash
assert user.check_password('my_password') # True because accepts a raw string
user.password
是 password
的散列和元数据。
根据docs,
check_password(raw_password)
Returns True if the given raw string is
the correct password for the user. (This takes care of the password
hashing in making the comparison.)
所以,只需将实际的原始字符串密码传递给user.check_password()
,单元测试就会通过。
正在尝试编写一个单元测试来检查用户是否输入了正确的密码。
为此使用 Django 的本机身份验证功能 user.check_password
。
问题是 check_password
出于某种原因不接受 user
对象自己的密码。例如,这会引发错误:
assert user.check_password(user.password), "Password doesn't match"
user.password
returns MD5 unicode 字符串。
有谁知道为什么这个检查不通过,怎么才能通过检查?
发生这种情况是因为 check_password
接受原始字符串并且您正在向它传递哈希值。
assert user.check_password(user.password) # False because passing hash
assert user.check_password('my_password') # True because accepts a raw string
user.password
是 password
的散列和元数据。
根据docs,
check_password(raw_password)
Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)
所以,只需将实际的原始字符串密码传递给user.check_password()
,单元测试就会通过。