使用simplejwt模块在django中修改jwt访问令牌到期时间

时间:2018-12-19 12:45:13

标签: django django-rest-framework jwt django-rest-framework-jwt

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 = datetime.timedelta(minutes=1)

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

@classmethod
def get_token(cls, user):        
    token = super(MyTokenObtainPairSerializer, cls).get_token(user)
    token['name']       = user.username
    token['user_id']    = user.id

    if user.is_superuser:
        #token.set_exp(from_time=starttime,lifetime=SUPERUSER_LIFETIME)
        token.payload['exp'] = datetime_to_epoch(token.current_time + SUPERUSER_LIFETIME)

    return token

class MyTokenObtainPairView(TokenObtainPairView):
     serializer_class = MyTokenObtainPairSerializer

我尝试过此代码(此链接之后:How can we assign different expiry time to different users in jwt tokens in django)。这段代码更新了刷新令牌的到期时间,但是我想使用simplejwt模块在django中更新访问令牌的到期时间。请提出任何建议。

1 个答案:

答案 0 :(得分:4)

我快速浏览了simplejwt github的页面,您可以在settings.py文件中自定义一些settings

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

根据评论更新答案

  

感谢您的回应。但是我想全局设置jwt的到期时间,然后根据角色设置,我想覆盖该到期时间。怎么可能??

正如您所说,您必须覆盖默认的令牌生成器方法。但是如何?

首先,创建您自己的令牌获取视图(继承自TokenObtainPairView)和您自己的令牌获取序列化程序(继承自TokenObtainPairSerializer)。之后,您可以看到validate方法创建了accessrefresh令牌,因此,如果要基于用户角色等创建令牌,则也必须覆盖该方法。还必须更改您的urls.py

示例;

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')
]