cod*_*ude 1 django django-rest-framework django-rest-framework-jwt
我正在使用django-rest-framework-simplejwt来获取access token和refresh token。
问题是,refresh token如果我更改用户的密码,它不会变得无效。refresh token基本上,即使用户更改密码后,我也可以继续发送和获取新的访问令牌。
我想要的是要求用户重新提交用户名和新密码以获得一对新的access和refresh tokens。
我将如何实现这个目标?
PS:只是因为我很好奇,这不应该是库的默认行为吗?在什么情况下我们希望保留refresh token凭据更改后的信息?
我想出了如何让它发挥作用。
我所做的就是放置一个信号来跟踪是否有任何所需的参数发生了变化。如果是这样,它会将与该用户关联的所有刷新令牌列入黑名单。
这是代码:
首先添加
'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)
Run Code Online (Sandbox Code Playgroud)
这段代码的主要作用是,获取用户的所有未完成的令牌,然后将它们全部添加到黑名单中。您可以在此处获取有关未偿还/黑名单代币的更多信息。 https://github.com/davesque/django-rest-framework-simplejwt#blacklist-app
| 归档时间: |
|
| 查看次数: |
2436 次 |
| 最近记录: |