为什么 django 的默认身份验证后端在引发 UserModel.DoesNotExist 异常后调用 set_password?

Why does default authentication backend of django calls set_password after raising UserModel.DoesNotExist exception?

我正在为从 Django 中的 AbstractUser 继承的自定义用户模型编写自定义身份验证后端。我已经通过 django 的默认身份验证后端,看到用户对象是使用带有 UserModel._default_manager.get_by_natural_key(username) authenticate() 的用户名获取的,如下所示

def authenticate(self, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
            if user.check_password(password):
                return user
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a non-existing user (#20760).
            UserModel().set_password(password)

我已经写了一个自定义的自动后端,但出于好奇我问这个,为什么在 DoesNotExist 异常时检查密码?

我已经在身份验证方法中尝试了 ipdb 并验证了在获取不存在的用户的用户名时,控制流会转到 except 块。并且 UserModel().set_password(password) 在终端发出。由于不确定后台发生了什么,我检查了 auth.modelsset_password() 代码。但它只是引发了一个 NotImplementedError 异常。我不确定这有什么帮助。

另外,如何 raise a UserDoesNotExist or django.core.exceptions.ObjectDoesNotExist exception correctly 在自定义身份验证后端中对用户模型的对象获取操作失败时?想法是停止执行并向用户提供正确的反馈消息,而不是引发异常并尝试下一个身份验证后端,如 settings.py.

中的 AUTHENTICATION_BACKENDS() 中给出的那样

TIA

你应该阅读这篇文章:

https://code.djangoproject.com/ticket/20760

When attempting to authenticate using django.contrib.auth, if a user does not exist the authenticate() function returns None nearly instantaneously, while when a user exists it takes much longer as the attempted password gets hashed and compared with the stored password. This allows for an attacker to infer whether or not a given account exists based upon the response time of an authentication attempt.

评论解释了原因。如果它立即返回 False,则与不存在的用户相比,它花费的时间要少得多。然后,攻击者将能够区分现有用户名和不存在的用户名。