'How to add custom claim in django rest_framework_simple_jwt?

Their official doc only shows implementation for class based views.

How to get this done for a function, ie. Refreshtoken.for_user()?

from rest_framework_simplejwt.tokens import RefreshToken

def get_tokens_for_user(user):

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

Snippet from here. This only shows how to create token manually.

I know using pyjwt would make life simpler but there will be another workaround for blacklisting.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Milon Mahato