我正在django中使用jwt令牌。我所有用户的有效时间为5分钟。但是我想根据角色更改用户的有效时间。如何使用SIMPLE JWT模块在Django中实现这一目标。
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
}
修改后的代码:
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
当我打印SUPERUSER LIFETIME时,它显示出10秒的差异。但是,当我尝试解码访问令牌时,它显示了默认时间300秒。这可能是什么问题?
答案 0 :(得分:0)
您可以尝试编写“自定义”视图:
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
还需要更新urls.py
url(r'^api/token/$', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),