Adding information to JWT token body using django rest framework jwt

Using the djangorestframework_simplejwt library

  1. Specify in settings.py the USER_ID_FIELD and ALGORITHM

    SIMPLE_JWT = {
        'USER_ID_FIELD': 'user_id',
        'ALGORITHM': 'HS512',
    }
    

Let's say you want to add fields to the body of TokenObtainPairView which has the following body

Token Obtain Pair body

{
    "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU5MDk5ODAwMSwianRpIjoiMjZhZThhYTU4YTJiNDU3M2JlMDgxNTMzMzU1ODg4ZmUiLCJ1c2VyX2lkIjoxMX0.-jUCnfpTF-RsqHnuoEgctPpHf1SfYNcYaPs8oo01RvrQBMcyhms5PfWipfYkaR0FlPHSTKncNeMxomwd4k7nyg",
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTExOTAxLCJqdGkiOiI5NjZkOTFhNzEzNjg0NjMyOGUzYWU3NThiNzNiZmYxMyIsInVzZXJfaWQiOjExfQ.LiHrekmlHrM7_5187ghpIaA6mKcPCjDz4MDKPXHc4QAKVGvcJCJpCjrODCB4-pZn4Kuai5ht3YjWwYSirxpsXw"
}
  1. Add in your urls.py

    path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain'),
    
  2. Create the MyTokenObtainPairView

    class MyTokenObtainPairView(TokenObtainPairView):
        serializer_class = MyTokenObtainPairSerializer`
    
  3. Create the MyTokenObtainPairSerializer

    class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
        def validate(self, attrs):
            data = super().validate(attrs)
            refresh = self.get_token(self.user)
            data['refresh'] = str(refresh)
            data.pop('refresh', None) # remove refresh from the payload
            data['access'] = str(refresh.access_token)
    
            # Add extra responses here
            data['user'] = self.user.username
            data['kind'] = self.user.kind
            data['date'] = datetime.date.today()
            return data
    

This way when you post to /api/token/ you'll get in the body something like this

{
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTEwNTc0LCJqdGkiOiIwM2Q5MzA1NTZmNzk0NmFjODU1MzJlNTYzNjUwZDY0MCIsInVzZXJfaWQiOjExfQ.H0huO84qtzdbo4OkKhsW_vtNTGwInG67gum6f138h1y66EiyZ1BvxaxbfEE2oPG4pB0XjiWQrXc5PlR9C6UvfQ",
    "user": "tiago",
    "kind": "whatever_this_has"
    "date": "2020-05-31"
}