【发布时间】:2020-03-08 15:41:17
【问题描述】:
我有一个非常简单的愿望:通过 REST 验证(登录)用户。我需要使用电子邮件和密码。
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'rest_framework',
'modeltranslation',
'corsheaders',
'django_s3_storage',
'rest_framework.authtoken',
'rest_auth',
'allauth',
'allauth.account'
]
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
urls.py:
re_path(r'^rest-auth/', include('rest_auth.urls')),
当我这样做时:
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{"email": "admin@test.com", "password": "zyzzyx' \
http://localhost:8000/rest-auth/login/
错误消息是:无法使用提供的凭据登录。
编辑:
我正在使用自定义用户模型:
class CustomUser(AbstractUser):
created = models.DateTimeField(auto_now_add=True)
username = models.CharField(max_length=100, unique=True)
email = models.EmailField(max_length=200, unique=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='%(class)s_company')
role = models.CharField(
max_length=100,
choices=ROLE_CHOICES,
default='admin',
)
class Meta:
ordering = ('created',)
db_table = "custom_user"
def __str__(self):
return self.username
User = get_user_model()
在settings.py中:
AUTH_USER_MODEL = 'myapps.CustomUser'
【问题讨论】:
-
您的
curl请求看起来不错。可能是凭证错误或login controller有问题。 -
凭据正确。我可以使用该密码和用户名 admin 登录 Django admin。
标签: django django-rest-framework