How can we assign different expiry time to differe

2019-08-24 05:29发布

问题:

i am using jwt tokens in django. i have expiry time 5mins for all the users.but i want to change the expiry time of the user based on the role. How can i achieve that in django using SIMPLE JWT module.

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,
    }

edited code:

  SUPERUSER_LIFETIME = datetime.timedelta(seconds=10)
  class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
            @classmethod
            def get_token(cls, user):
                            token = super(MyTokenObtainPairSerializer, cls).get_token(user)
                            starttime              = datetime.datetime.now()
                            timelimit              = datetime.timedelta(seconds=10)
                            endtime               = (timelimit + datetime.datetime.now())
                            expirytime = int(endtime.timestamp())
                            token['name']                   = user.username
                            token['user_id']                = user.id
                            if user.is_superuser:
                                            print("EXPIRY TIME ",expirytime)
                                            print("SUPERUSER LIFETIME ",SUPERUSER_LIFETIME)
                                            token.set_exp(lifetime=SUPERUSER_LIFETIME)
                            return token
  class MyTokenObtainPairView(TokenObtainPairView):
            serializer_class = MyTokenObtainPairSerializer

when i print SUPERUSER LIFETIME it is showing difference of 10sec .But,when i try to decode the access token it is showing the default time of 300sec. what can be the problem here?

回答1:

You can try to write your Custom view:

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

SUPERUSER_LIFETIME = timedelta(minutes=60)

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super(MyTokenObtainPairSerializer, cls).get_token(user)
        if user.is_superuser:
            token = token.access_token
            token.set_exp(lifetime=SUPERUSER_LIFETIME)
        return token

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

Also you need to update your urls.py

url(r'^api/token/$', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),


标签: django jwt