我正在设置django以发送jwt响应,而不是视图。我尝试使用django rest框架simplejwt。
在这个框架中,有一个函数TokenObtainPairView.as_view()返回一对jwt。我需要用另一个json响应返回访问令牌,而不是提供的两个令牌。
理想情况下,我希望一个jsonresponse包含与此相同的访问令牌:TokenObtainPairView.as_view()
我试着创建自己的视图,如下所示。
更新:在settings.py中提供

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(days=1),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

登录URL路径
urlpatterns = [
    path('auth/', views.LoginView.as_view()),
]

我创建的loginview
class LoginView(APIView):
    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):
        username = request.data['username']
        password = request.data['password']

        user = authenticate(username=username, password=password)

        if user is not None:
            payload = {
                'user_id': user.id,
                'exp': datetime.now(),
                'token_type': 'access'
            }

            user = {
                'user': username,
                'email': user.email,
                'time': datetime.now().time(),
                'userType': 10
            }

            token = jwt.encode(payload, SECRET_KEY).decode('utf-8')
            return JsonResponse({'success': 'true', 'token': token, 'user': user})

        else:
            return JsonResponse({'success': 'false', 'msg': 'The credentials provided are invalid.'})

框架提供的模式。
urlpatterns = [
...
path('token/', TokenObtainPairView.as_view()),
...
]

它返回这个令牌
EYJ0exaijkv1qilcjbGCioijiuzi1nij9.eyj0b2tlbl90exblijoiywnjxnziiwizxhwijoxntq5ndk3ndq2lcjqdgkiiii3ymu4yzkzode4mjmjndjmdhzmzuxyinsinvzzxjfawqioiin0.xvfdrwf26g4fzl2zx3njpi7tju6qxpybjq-vh1ft0xs
EYJ0exaijkv1qilcjhbgcioijiuzi1nij9.eyj0b2tlbl90exblijoicmvmcmvzacisimv4cci6mtu0otq5nzq0niwianrpijioiotnhyzkxmju5nmzkndyjg2ogq0ztm2zjkmjhodcilcj12v2vyx2lkijoicj9.douyufumjkviri2眙ucxt8眙alcjlxnairjx8ehqdibcg
如果你去https://jwt.io/你会看到返回的内容

最佳答案

例如:要通过添加用户名和组自定义simplejwt响应,
json - 从django-rest-framework-simplejwt定制JWT响应-LMLPHP
重写validate中的TokenObtainPairSerializer方法

# project/views.py

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = self.get_token(self.user)
        data['refresh'] = str(refresh)
        data['access'] = str(refresh.access_token)

        # Add extra responses here
        data['username'] = self.user.username
        data['groups'] = self.user.groups.values_list('name', flat=True)
        return data


class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

用自定义视图替换登录视图
# project/urls.py

from .views import MyTokenObtainPairView

urlpatterns = [
    # path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
]

γ
参考文献:SimpleJWT Readme和源代码如下:
json - 从django-rest-framework-simplejwt定制JWT响应-LMLPHP

09-27 17:32