0

我在 Django 中使用 simpleJWT 身份验证。默认情况下,响应是这样的:

{ "refresh"=""
  "access"= ""
}

我想自定义响应没有标题并包含一些用户详细信息,例如

{
    username: ' ',
    detail1: ' ',
    detail2: ' ',
    accessToken: ' ',
    refreshToken: ' '
} 

如何使用 simpleJWT 实现这样的响应?

4

1 回答 1

0

如果要自定义,可以为api编写自己的视图,不需要使用现有的

从文档 https://django-rest-framework-simplejwt.readthedocs.io/en/latest/creating_tokens_manually.html创建令牌

序列化程序.py:

from rest_framework import serializers, viewsets, status

class SignInSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=255, required=True)
    password = serializers.CharField(max_length=255, required=True, write_only=True)

视图.py

from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.views import APIView
from django.http import JsonResponse
from django.contrib.auth import authenticate


class signin(APIView):
    permission_classes = ()
    authentication_classes = ()

    def post(self, request):
        received_json_data=request.data
        serializer = SignInSerializer(data=received_json_data)
        if serializer.is_valid():
            user = authenticate(
                request, 
                username=received_json_data['username'], 
                password=received_json_data['password'])
            if user is not None:
                refresh = RefreshToken.for_user(user)
                return JsonResponse({
                    'refresh': str(refresh),
                    'access': str(refresh.access_token),
                    # your other stuffs <- add here
                }, status=200)
            else:
                return JsonResponse({
                    'message': 'invalid username or password',
                }, status=403)
        else:
            return JsonResponse({'message':serializer.errors}, status=400)
于 2020-12-04T11:09:08.000 回答