Django Rest Framework Simple JWT


1. Customizing the payload

from rest_framework_simplejwt.tokens import RefreshToken

def my_jwt_payload_handler(user):
    return {
        'user_id': user.id,
        'username': user.username,
        'email': user.email,
        # Custom claims
        'role': user.role,
        'permissions': [permission.codename for permission in user.get_all_permissions()],
    }

2. Overriding the token blacklist

from rest_framework_simplejwt.authentication import JWTAuthentication, JWTTokenUserAuthentication

class CustomJWTAuthentication(JWTAuthentication):
    def authenticate(self, request):
        # Get the token from the request
        token = self.get_jwt_value(request)

        if token is None:
            return None

        # Decode the token
        try:
            payload = self.get_validated_token(token)
        except:
            return None

        # Check if the token is blacklisted
        if payload['jti'] in self.blacklist:
            return None

        # Get the user from the payload
        user = self.get_user(payload)

        if user is None:
            return None

        return self.authenticate_credentials(payload, user)

3. Adding custom authentication backends

4. Using custom tokens

5. Creating custom tokens in views

6. Using the JWT token in custom views

7. Overriding the token verification behavior

8. Using a custom token encoder