我正在使用 Simple JWT在我的 Django rest API 中使用 JWT token 。它工作得很好,但我希望能够在用户注销时将 token 列入黑名单。在文档中说:
If the blacklist app is detected in INSTALLED_APPS, Simple JWT will add any generated refresh or sliding tokens to a list of outstanding tokens. It will also check that any refresh or sliding token does not appear in a blacklist of tokens before it considers it as valid. The Simple JWT blacklist app implements its outstanding and blacklisted token lists using two models: OutstandingToken and BlacklistedToken. Model admins are defined for both of these models. To add a token to the blacklist, find its corresponding OutstandingToken record in the admin and use the admin again to create a BlacklistedToken record that points to the OutstandingToken record.
但是,我没有找到任何代码示例,而且我不确定应该如何实现它。一个例子将不胜感激。
最佳答案
Simple JWT 仅黑名单刷新 token 。这可以通过设置来完成:
INSTALLED_APPS = (
...
'rest_framework_simplejwt.token_blacklist',
...
}
然后运行 migrate
。
所以,我建议,为了注销用户:
从客户端删除刷新和访问 token 。此外,尽可能缩短访问 token 的有效期。
通过创建 api 端点将刷新 token 列入黑名单。
网址.py
path('/api/logout', views.BlacklistRefreshView.as_view(), name="logout"),
View .py
from rest_framework_simplejwt.tokens import RefreshToken class BlacklistRefreshView(APIView): def post(self, request) token = RefreshToken(request.data.get('refresh')) token.blacklist() return Response("Success")
这将确保不能再次使用刷新 token 来生成新 token (如果有人已经获得了它)。此外,由于访问 token 的生命周期很短,因此希望它很快就会失效。
关于django - 如何使用 Simple JWT (django rest) 将 JWT token 列入黑名单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58010776/