如何使用 Django Simple JWT 为具有负载的用户获取令牌

How to obtain a token for a user with payload using Django Simple JWT

我在调用 URL /token/ 时可以获得正确的令牌,但我希望在调用 /login/ 时为用户手动创建一个令牌。

urls.py:

    from django.urls import path
    from . import views
    from .views import MyTokenObtainPairView

    from rest_framework_simplejwt.views import (
        TokenRefreshView,
        TokenVerifyView
    )

    urlpatterns = [
        path('', views.api_root),
        path('register/', views.register),
        path('login/', views.login),
        path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
        path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
        path('token/verify/', TokenVerifyView.as_view(), name='token_verify'),
    ]

views.py:

@api_view(['POST'])
def login(request):
    email = request.data.get('email')
    password = request.data.get('password')
    user = get_object_or_404(User, email=email)

    if make_password(password) == user.password:
        if not user.is_active:
            return Response({"error": "User is not active"}, status=400)
        tokens = MyTokenObtainPairView.get_token(user)
        parse_token = {
            'refresh': str(tokens),
            'access': str(tokens.access_token),
        }
        return Response(status=200, data=parse_token)
    else:
        return Response(status=401)

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)
        data['test'] = '1234'
        return data

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

如何修改此行以获取特定用户的令牌? tokens = MyTokenObtainPairView.get_token(user)

我已阅读有关通过导入以下内容手动创建令牌的文档: from rest_framework_simplejwt.tokens import RefreshToken 但它没有将有效负载添加到令牌中...

实际上在谷歌搜索了一个小时后,我终于从另一个 post...

那里得到了解决方案

正确的做法:

    refresh = RefreshToken.for_user(user)
    refresh['user_name'] = user.username
    refresh['first_name'] = user.first_name
    refresh['last_name'] = user.last_name
    refresh['full_name'] = user.get_full_name()
    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }

万一有人需要这个...