我想出了如何让这个工作。
我所做的是放置一个信号来跟踪是否有任何必需的参数发生了变化。如果是这样,它将与该用户关联的所有刷新令牌列入黑名单。
这是代码:
首先添加'rest_framework_simplejwt.token_blacklist'
已安装的应用程序。然后:
@receiver(signals.pre_save, sender=User)
def revoke_tokens(sender, instance, update_fields, **kwargs):
if not instance._state.adding: #instance._state.adding gives true if object is being created for the first time
existing_user = User.objects.get(pk=instance.pk)
if instance.password != existing_user.password or instance.email != existing_user.email or instance.username != existing_user.username:
# If any of these params have changed, blacklist the tokens
outstanding_tokens = OutstandingToken.objects.filter(user__pk=instance.pk)
# Not checking for expiry date as cron is supposed to flush the expired tokens
# using manage.py flushexpiredtokens. But if You are not using cron,
# then you can add another filter that expiry_date__gt=datetime.datetime.now()
for out_token in outstanding_tokens:
if hasattr(out_token, 'blacklistedtoken'):
# Token already blacklisted. Skip
continue
BlacklistedToken.objects.create(token=out_token)
这段代码的基本作用是,为用户获取所有未完成的令牌,然后将它们全部添加到黑名单中。您可以在此处获取有关未完成/列入黑名单的代币的更多信息。
https://github.com/davesque/django-rest-framework-simplejwt#blacklist-app