The easiest way I always followed is here. You may see that the Token class in rest_framework_simplejwt implemented __setitem__ and __getitem__. So easily you can add a claim to your token.
You have to make a customer serializer that will extend the TokenObtainSerializer class. See the code for a better understanding:
serializers.py:
class MyTokenObtainPairSerializer(TokenObtainSerializer):
token_class = RefreshToken
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
refresh["my_claim"] = "value" # here you can add custom cliam
data["refresh"] = str(refresh)
data["access"] = str(refresh.access_token)
return data
And then create a view that will extend the TokenViewBase class:
views.py
class MyTokenObtainPairView(TokenViewBase):
serializer_class = MyTokenObtainPairSerializer
urls.py
urlpatterns = [
path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
]
Here we go, Done.
After doing those steps and decoding the access token you will find something link this:
{
"token_type": "access",
"exp": 1651785191,
"iat": 1651784891,
"jti": "8432cb561ef0467e909e4a4c05234b71",
"user_id": 1,
"my_claim": "value"
}
For more, you can see this repo. Here I did a project following the rest_framework_simplejwt package for learning and understanding the custom authentication backend.