Search code examples
pythondjangodjango-rest-frameworkjwtpyjwt

Adding information to JWT token body using django rest framework jwt


Im using django rest framework and the djangorestframework-jwt package to creat JWT tokens for authorization.

On the frontend I can decode the token and get the username, email and user_id. However I would like to retrieve some extra information. For example it would be very convenient if I could get kind which is a field on our authorization model (user model).

I can ofcourse make a separate request to get the user info via a regular APIView. But I'm wondering if it's possible to add some extra params in the JWT body?


Solution

  • As detailed in this github issue, I did this by subclassinng the ObtainJSONWebToken class from DRF-JWT:

    from rest_framework_jwt import views as jwt_views
    from .serializers import UserSerializer 
    
    class UserLoginViewJWT(jwt_views.ObtainJSONWebToken):
        user_serializer_class = UserSerializer
    
        def post(self, request, *args, **kwargs):
            response =  super().post(request, *args, **kwargs)
    
            if response.status_code == status.HTTP_200_OK:
                user = get_user_model().objects.get(email=request.data[get_user_model().USERNAME_FIELD])
                serialized_user = self.user_serializer_class(user)
                response.data.update(serialized_user.data)
            return response
    

    Note: the code above is probably missing some imports

    A reply from @jpadilla also specified that

    You can also do this with the JWT_RESPONSE_PAYLOAD_HANDLER setting. http://getblimp.github.io/django-rest-framework-jwt/#jwt_response_payload_handler