Customizing token claims

If you wish to customize the claims contained in web tokens which are generated by the TokenObtainPairView and TokenObtainSlidingView views, create a subclass for the desired view as well as a subclass for its corresponding serializer. Here’s an example of how to customize the claims in tokens generated by the TokenObtainPairView:

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # Add custom claims
        token['name'] = user.name
        # ...

        return token

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

Note that the example above will cause the customized claims to be present in both refresh and access tokens which are generated by the view. This follows from the fact that the get_token method above produces the refresh token for the view, which is in turn used to generate the view’s access token.

As with the standard token views, you’ll also need to include a url route to your subclassed view.