我们如何在Django的jwt令牌中为不同的用户分配不同的到期时间
问题描述:
我正在django中使用jwt令牌.我对所有用户都有5分钟的到期时间,但是我想根据角色更改用户的到期时间.如何使用SIMPLE JWT模块在Django中实现这一目标.
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,
}
修改后的代码:
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秒时间.这可能是什么问题?
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?
答
您可以尝试编写自定义"视图:
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
还需要更新您的urls.py
url(r'^api/token/$', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),