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:
- Install the necessary libraries: Make sure you have
djangorestframework
anddjangorestframework-simplejwt
installed.pip install djangorestframework djangorestframework-simplejwt
- Update your Django settings: Configure
django-simple-jwt
in yoursettings.py
file.INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework_simplejwt', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), }
- 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
- 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
- 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'), ]
- Test your custom claim: Now when you obtain a token, it should include your custom claim.