Django REST framework smiple jwt add custom payload data and access it in route

742 views Asked by At

I am generating a custom jwt token for authentication using RefreshToken.for_user(user) at the time of login and registration. I can access user using request.user in the API endpoint but I also want to add user type in the payload data, so that I can access the user_type field in the API endpoint.

This is what I am doing.

def get_tokens_for_user(user):
  refresh = RefreshToken.for_user(user)
  return {
      'refresh': str(refresh),
      'access': str(refresh.access_token),

class UserRegistrationView(APIView):
  def post(self, request, format=None):
    serializer.is_valid(raise_exception=True)
    token = get_tokens_for_user(user)
    return Response({ 'token':token })

Now at endpoint

class FileDetail(APIView):
    permission_classes = (IsAuthenticated,)
    def get(self, request, pk):
        user = request.user
        user_type = request.user_type // this data I want to save in the payload and get here.

so I want user_type and other data at API endpoint from jwt payload data

1

There are 1 answers

5
Tanveer On

this is how you add custom payload.

  • import TokenOBtainPairSerializer

    from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomeTokenObtainPairSerializer(TokenObtainPairSerializer):

    def validate(self, attrs):
        data = super(CustomeTokenObtainPairSerializer, self).validate(attrs)
        if self.user.is_active is not True:
            raise serializers.ValidationError({"message": "User is not active."})
        data.update({
            'username': self.user.username,   # username
            'email': self.user.email,       # email
            'mobile_number': self.user.mobile_number  # mobile_number
                **## here add more fields as you want**
        })
        return data