修改 simpleJWT 响应

Modify simpleJWT response

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

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

我想将响应自定义为不包含 header 并包含一些用户详细信息 例如

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

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

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

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

serializer.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)

views.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)