How to add custom claim in django rest_framework_simple_jwt?

1.8k Views Asked by At

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.

3

There are 3 best solutions below

2
On

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.

0
On

The easiest way to add custom claims in the manually generated token is:

serializers.py

# User Serializer
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        exclude = ('password',)

views.py

from rest_framework_simplejwt.tokens import RefreshToken
from .serializers import UserSerializer

def get_tokens_for_user(user):
  refresh = RefreshToken.for_user(user)

  #Add custom claims
  refresh["user"] = UserSerializer(user).data

  return {
      'refresh_token': str(refresh),
      'access_token': str(refresh.access_token),
  }
0
On
refresh = RefreshToken.for_user(user)
refresh["first_name"] = str(user.first_name) //any field or data

To add custom fields in decode of access token , we add like this enter image description here