Search code examples
django-rest-frameworkdjango-rest-framework-simplejwt

Exp or iat time in rest_framework_simplejwt token


How to get jwt token expiration time or issuing time, in Django rest framework simple jwt library. I need to pass token expiration time in response to the client.


Solution

  • You'll have to write a custom serializer. If it is the TokenObtainPairView view for which you want to return the token's expiry time, for example, create a custom view that inherits from TokenObtainPairView and a custom serializer that inherits from TokenObtainPairSerializer.

    For example:

    In your urlpatterns:

    path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
    

    Custom view:

    from rest_framework_simplejwt.views import TokenObtainPairView
    
    
    class CustomTokenObtainPairView(TokenObtainPairView):
        serializer_class = CustomTokenObtainPairSerializer
    

    Custom serializer:

    from datetime import datetime
    
    from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
    
    class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
        def validate(self, attrs):
            data = super().validate(attrs)
    
            refresh = self.get_token(self.user)
    
            data['refresh'] = str(refresh)
            data['access'] = str(refresh.access_token)
    
            # Add custom data here
    
            data['access_token_lifetime'] = str(refresh.access_token.lifetime)
            data['access_token_expiry'] = str(datetime.now() + refresh.access_token.lifetime)
    
            if api_settings.UPDATE_LAST_LOGIN:
                update_last_login(None, self.user)
    
            return data