我有一个 Django 项目,其中使用 Django-rest-auth 进行身份验证。我想使用 带密码的电子邮件 来验证用户身份,而不是用户名+密码。
我的settings.py中有以下设置,但它对我没有任何作用:
REST_SESSION_LOGIN = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'EMAIL'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
我怎样才能实现它?
以下设置有效:
#This is required otherwise it asks for email server
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# ACCOUNT_EMAIL_REQUIRED = True
# AUTHENTICATION_METHOD = 'EMAIL'
# ACCOUNT_EMAIL_VERIFICATION = 'optional'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
#Following is added to enable registration with email instead of username
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
我也在使用这个包,通过调用这个配置它对我有用:
ACCOUNT_AUTHENTICATION_METHOD = 'email'
小心这个配置,这个配置属于
django-allauth
,看这个:
class AuthenticationMethod:
USERNAME = 'username'
EMAIL = 'email'
USERNAME_EMAIL = 'username_email'
上面的类是
allauth
中的设置,所以你应该小写'EMAIL'。
Django 维护一个检查身份验证的“身份验证后端”列表。如果一种身份验证方法失败,Django 将尝试其他方法。
默认
django.contrib.auth.backends.ModelBackend
要求您提供用户名。如果您想为其添加自定义功能,则需要添加另一个身份验证后端。对于您的用例,allauth.account.auth_backends.AuthenticationBackend
因此,修改
AUTHENTICATION_BACKENDS
设置如下:
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
您可以在此处阅读有关自定义身份验证后端的更多信息: https://docs.djangoproject.com/en/5.1/topics/auth/customizing/