了解 AUTHENTICATION_BACKENDS

Understanding AUTHENTICATION_BACKENDS

当我在 settings.py 中写下以下内容时,我试图理解事情是如何进行的:

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
    "master_password.auth.ModelBackend"
)

特别是 documentation 状态:

If a backend raises a PermissionDenied exception, authentication will immediately fail. Django won’t check the backends that follow.

鉴于此,当用户输入错误的密码并且第一后端拒绝他访问时,上面示例中的第二和第三后端如何获得机会?更具体地说,第三个后端属于 django-master-password,如果用户使用主密码,即使它与用户的密码不匹配,它也应该让用户进入。那么,后端将如何获得机会?

来自docs

Django tries authenticating across all of its authentication backends. If the first authentication method fails, Django tries the second one, and so on, until all backends have been attempted.

django.contrib.auth.backends.ModelBackend(如果我没记错的话)不会引发 PermissionDenied,因此如果验证失败,将使用后续的验证后端,直到找到匹配项。

The order of AUTHENTICATION_BACKENDS matters, so if the same username and password is valid in multiple backends, Django will stop processing at the first positive match.

如果您发现它确实提高了 PermissionDenied,那么该模型后端可能最好放在 AUTHENTICATION_BACKENDS 列表的末尾。