[Fixed]-Modifying jwt access token expiry time in django using simplejwt module

30πŸ‘

βœ…

I just made a quick look to simplejwt github’s page and you can customize some settings in your settings.py file;

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
}

Updated Answer Based On Comment

thanks for response . but i want set globally jwt expiry time and later based on role , i want to override that expiry time . how is it possible??

As you say, you have to override default token generator method. But how?

First, create your own token obtain view that inherited from TokenObtainPairView and your own token obtain serializer that inherited from TokenObtainPairSerializer. After that, you can see that validate method create access and refresh tokens, so also you must override that method if you want to create token based on user role etc. After these steps you also have to change your urls.py.

Example;

import datetime

from django.utils.six import text_type

from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

SUPERUSER_LIFETIME = datetime.timedelta(minutes=1)


class MyTokenObtainSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data = super(TokenObtainPairSerializer, self).validate(attrs)
        refresh = self.get_token(self.user)
        data['refresh'] = text_type(refresh)
        if self.user.is_superuser:
            new_token = refresh.access_token
            new_token.set_exp(lifetime=SUPERUSER_LIFETIME)
            data['access'] = text_type(new_token)
        else:
            data['access'] = text_type(refresh.access_token)
        return data


class MyTokenObtainView(TokenObtainPairView):
    serializer_class = MyTokenObtainSerializer

urls.py

urlpatterns = [
    path('api/token/', MyTokenObtainView.as_view(), name='token_obtain_pair')
]
πŸ‘€uedemir

Leave a comment