DFR 简单 jwt 从用户实例而不是 username/password 获取 authToken

DFR simple jwt get authToken from a user instance instead of username/password

我有一个简单的聊天应用程序,其中的身份验证与 whatsapp 一样有效

获取 phone 号码 => 如果不存在则创建其他号码 skip => 发送验证码并将其设置为用户模型中的“phone_code”字段 => 最后删除“phone_code" 如果经过验证

该应用程序是在 React Native 中构建的,Rest 框架作为 API,我是新手,我正在努力获取没有密码的身份验证令牌。我使用 djangorestframework-simplejwt

我的注册视图:

@api_view(('POST',))
def register(request):
    if request.method == 'POST':
        serializer = UserSerializer(data=request.data)
        if not serializer.is_valid():
            if 'is not valid' in serializer.errors['phone_number'][0]:
                return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
        phone_number = serializer.initial_data['phone_number'].replace(' ', '')
        try:
            user = User.objects.get(phone_number=phone_number)
        except User.DoesNotExist:
            user = User.objects.create_user(
                phone_number=phone_number, username=phone_number)
        user.phone_code = randint(99999, 999999)
        user.save()
        TokenObtainPairView()
        return Response(serializer.data, status.HTTP_200_OK)
        # todo send validation code, I will handle later

我的登录视图(Chich验证验证码)

@api_view(['POST',])
def loginuser(request):
    if request.method == 'POST':
        phone_number = request.data.get('phone_number')
        try:
            user = User.objects.get(phone_number=phone_number)
            if int(request.data.get('phone_code')) == user.phone_code and user.phone_code:
                user.phone_code = None
                user.save()
                #!!!!!!!!!!!!!!!!!!!NOW HOW CAN I GET THE JWT AUTHENTICATION TOKEN AND SEND IT TO MY REACT NATIVE APP?!
                return JsonResponse({'phone_number': phone_number}, status=200)

            else:
                return JsonResponse({'error': "Invalid code"}, status=400)
        except Exception as error:
                return JsonResponse({'error': error}, status=500)

当用户验证他的 phone 号码时,我如何将 jwt 格式的身份验证令牌与响应一起发送?

urls.py:

path('api/token/', users_views.ObtainToken.as_view(), name='token_obtain_pair'),

我的自定义 obtainToken 视图:

class ObtainToken(TokenObtainPairView):
    permission_classes = (AllowAny,)
    serializer_class = MyTokenObtainPairSerializer

我还发现,当我使用 Postman 时,如果我发送一个空密码,系统将提供一个身份验证令牌。如果有任何帮助,我将不胜感激,谢谢

您的代码应基于 rest_framework_simplejwt 中的现有视图和序列化器:使用 TokenObtainPairView 是一个好的开始,请保留它。

那么在你的seriliazer_class、MyTokenObtainPairSerializer中,你应该使用TokenObtainSerializer

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    def validate(self, attrs):
        self.user = User.objects.get(phone_number=phone_number)
        # Do the verification with the phone_code here, if error, return a response with an error status code

        refresh = self.get_token(self.user)

        data['refresh'] = text_type(refresh)
        data['access'] = text_type(refresh.access_token)

        return data