1

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 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I said that you will get your claim after decoding the encoded token. It will not add the field with the response. The response will be the same as before, in this case, the access token and refresh token. And for the function base, it will be the same way. refresh["something"] = "something"
2

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),
  }

Comments

1
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

1 Comment

You saved my world! I want to add custom claims in the payload, this works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.