1

how to validate the JWT token in Simple JWT authentication. I need to verify when the user sends a request if the token access token is expired so it will redirect him to refresh the token.

serializers.py

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        # The default result (access/refresh tokens)
        data = super(CustomTokenObtainPairSerializer, self).validate(attrs)
        # Custom data you want to include
        data.update({'email': self.user.email})
        data.update({'id': self.user.id})
        data.update({'status':"success"})
        # and everything else you want to send in the response
        return data

views.py

class CustomTokenObtainPairView(TokenObtainPairView):
    # Replace the serializer with your custom
    serializer_class = CustomTokenObtainPairSerializer

urls.py

from rest_framework_simplejwt.views import TokenRefreshView, TokenVerifyView

urlpatterns = [
  
  
    path('token/', views.CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('token/verify/', TokenVerifyView.as_view(), name='token_verify'),
    
]

urlpatterns = format_suffix_patterns(urlpatterns)

Ali Rn
  • 1,114
  • 8
  • 19
Zero0
  • 371
  • 4
  • 15
  • Can you please explain what problem you have? Anything wrong with the code? – jps Aug 27 '21 at 15:14
  • I need to liké add a middleware to a simple jwt authentication , so for the first Time thé user login in je recieves an Access Token and a refreshet Token, and when je triés to for example add a New post , he sends thé Access Token in thé request, i need to first verify if thé Token is not expired, if it is expired then i redirect him to thé refresh Token endpoint otherwise , hé Can add the post , and i need to do it with http only cookies in simple jwt , i searchef a lot but i dont know if i Can Do it with this library – Zero0 Aug 28 '21 at 08:13

1 Answers1

0

You must add jwt authentication middleware in your settings.py authentication class for rest framework.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
         ...
)
Ashin Shakya
  • 690
  • 6
  • 9