【问题标题】:How to authenticate user via REST using email and password with Django Rest Framework如何使用 Django Rest Framework 使用电子邮件和密码通过 REST 对用户进行身份验证
【发布时间】: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


【解决方案1】:

为了使用django_rest_framwork 的内置方法进行令牌认证,您应该调用obtain_auth_token 方法。

所以,你的 urls.py 看起来像

from django.urls import path
from rest_framework.authtoken.views import obtain_auth_token  # <-- Here
from myapi.core import views

urlpatterns = [
    path('rest-auth/', obtain_auth_token, name='api_token_auth'),  # <-- And here
]

更多详情请参考this tutorial

更新 1

您似乎没有正确配置rest_auth,这就是您登录失败的原因。您应该将REST_SESSION_LOGIN 设置为True 以进行会话身份验证。如果需要令牌认证,请将REST_USE_JWT 设置为True。有关所有可用配置,请参阅 this documentation

【讨论】:

  • 我想我可以应付 SessionAuthentication,而不是令牌。
  • 您能分享一下rest_auth 的设置吗?我看到包正在根据设置处理django_login。可以看源码here
  • 如果我关注你,我认为我目前与 rest_auth 相关的所有设置都包含在原始问题中。我错过了什么吗?
  • 您应该将REST_SESSION_LOGIN 设置为True 以进行会话身份验证。
  • REST_SESSION_LOGIN 的默认值为 True。
【解决方案2】:

我最终也在用户名字段中存储了电子邮件地址。

【讨论】:

    猜你喜欢
    • 2017-01-18
    • 2020-09-13
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    相关资源
    最近更新 更多