Add a custom claim to the JWT in Django

Adding a custom claim to the JSON Web Tokens (JWT) in Django using the django-simple-jwt library involves extending the token creation process to include additional information. Here’s how you can achieve this:

  1. Install the necessary libraries: Make sure you have djangorestframework and djangorestframework-simplejwt installed.
    pip install djangorestframework djangorestframework-simplejwt
    
  2. Update your Django settings: Configure django-simple-jwt in your settings.py file.
    INSTALLED_APPS = [
        ...
        'rest_framework',
        'rest_framework_simplejwt',
    ]
    
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework_simplejwt.authentication.JWTAuthentication',
        ),
    }
    
  3. Create a custom claims serializer: Extend the TokenObtainPairSerializer to include your custom claim.
    from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
    
    class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    
        def get_token(self, user):
            token = super().get_token(user)
    
            # Add custom claims
            token['custom_claim'] = 'custom_value'
            
            # Example: Add user's email to the token
            token['email'] = user.email
    
            return token
    
  4. Create a custom view: Use the custom serializer in your view.
    from rest_framework_simplejwt.views import TokenObtainPairView
    from .serializers import MyTokenObtainPairSerializer
    
    class MyTokenObtainPairView(TokenObtainPairView):
        serializer_class = MyTokenObtainPairSerializer
    
  5. Update your URLs: Include the custom view in your URL configuration.
    from django.urls import path
    from .views import MyTokenObtainPairView
    from rest_framework_simplejwt.views import TokenRefreshView
    
    urlpatterns = [
        path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
        path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    ]
    
  6. Test your custom claim: Now when you obtain a token, it should include your custom claim.