首页 > 解决方案 > 在测试期间,当使用正确的用户输入进行测试时,我得到“无效的凭据”

问题描述

我只使用电话号码作为登录的唯一字段。即使提供了正确的用户输入,身份验证似乎也无法正常工作。

配置 AUTH 后端时出错:

 File "C:\Users\UBITEK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 161, in __init__
    raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def logins(request):
    phone_number = request.data.get("phone_number")
    if phone_number is None:
        return Response({'error': 'Please provide your phone number'},
                        status=HTTP_400_BAD_REQUEST)
    user = authenticate(phone_number=phone_number)
    if not user:
        return Response({'error': 'Invalid Credentials'},
                        status=HTTP_404_NOT_FOUND)
    token, _ = Token.objects.get_or_create(user=user)
    return Response({'token': token.key},
                    status=HTTP_200_OK)

后端.py

from django.contrib.auth.backends import ModelBackend
from .models import User

class LoginBackend(ModelBackend):
    def authenticate(self, request, **kwargs):
        phone_number= kwargs['phone_number']
        user = User.objects.get(phone_number=phone_number)
        if user:
            return user
        else:
            return None

设置.py

from .backends import LoginBackend
from django.contrib.auth.backends import ModelBackend
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend',
    'findr.backends.LoginBackend']

标签: djangopython-3.xdjango-rest-framework

解决方案


关于对您问题的评论,我建议您编写自己的django身份验证后端:

https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#writing-an-authentication-backend

你必须告诉 Django 如何对某人进行身份验证:

  • 和?username_password
  • 和?phone_number_password

这必须是明确的(并且不要忘记将此新后端添加到您的settings.py文件中!)。


推荐阅读