djangodjango-rest-frameworkjwt

JWT token claims in Django Rest Framework


I am using rest_framework_simplejwt, and would like to add extra information to the access token returned for authorization purposes. Following along with https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html I am able to modify the access token. However I want to be able to add a claim based on the initial POSTed login. For example:

curl -X POST -H 'Content-type: application/json' -d '{"username": "user1", "password": "supersecretpassword", "project": "project1"}' https://myurl.com/api/token/

I would like to be able to add project1 to the access token. Is there a way to add extra information in that manner?


Solution

  • Added project field to TokenObtainSerializer.

    CustomTokenObtainPairSerializer has added the process of adding project values to the token payload in TokenObtainPairSerializer.

    serializers.py

    from django.contrib.auth.models import update_last_login
    from rest_framework_simplejwt.tokens import RefreshToken
    from rest_framework_simplejwt.settings import api_settings
    from rest_framework_simplejwt.serializers import TokenObtainSerializer
    from rest_framework import serializers
    
    
    class CustomTokenObtainSerializer(TokenObtainSerializer):
      
      def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.fields["project"] = serializers.CharField()
        
    class CustomTokenObtainPairSerializer(CustomTokenObtainSerializer):
      token_class = RefreshToken
    
      def validate(self, attrs):
          data = super().validate(attrs)
          refresh = self.get_token(self.user)
          refresh["project"] = attrs["project"]
    
          data["refresh"] = str(refresh)
          data["access"] = str(refresh.access_token)
    
          if api_settings.UPDATE_LAST_LOGIN:
              update_last_login(None, self.user)
          return data
    

    To make the above Serializer class available in TokenOptainPairView, I modified the setting values related to settings.py SIMPLE_JWT.

    settings.py

    SIMPLE_JWT = {
      ...
      "TOKEN_OBTAIN_SERIALIZER": "yourapp.serializers.CustomTokenObtainPairSerializer",
      ...
    }
    

    enter image description here

    enter image description here