django-rest-framework - rest_framework_simplejwt 令牌中的 Exp 或 iat 时间
问题描述
如何获取 jwt 令牌过期时间或发布时间,在 Django REST 框架简单的 jwt 库中。我需要传递令牌到期时间以响应客户端。
解决方案
You'll have to write a custom serializer. If it is the TokenObtainPairView
view for which you want to return the token's expiry time, for example, create a custom view that inherits from TokenObtainPairView
and a custom serializer that inherits from TokenObtainPairSerializer
.
For example:
In your urlpatterns
:
path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
Custom view:
from rest_framework_simplejwt.views import TokenObtainPairView
class CustomTokenObtainPairView(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer
Custom serializer:
from datetime import datetime
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
# Add custom data here
data['access_token_lifetime'] = str(refresh.access_token.lifetime)
data['access_token_expiry'] = str(datetime.now() + refresh.access_token.lifetime)
if api_settings.UPDATE_LAST_LOGIN:
update_last_login(None, self.user)
return data
推荐阅读
- python-3.x - Python相对路径和绝对路径
- spring - 哪个千分尺用于从 Spring 公开简单的静态应用程序(非数字)信息?
- playwright - 运行“npx folio”时出错:第一个参数必须使用对象解构模式:_x
- javascript - Mysql insert into 语句适用于除节点 js 客户端之外的任何地方
- javascript - 在一个反应组件中调用两个 API 调用
- angular - 如果清除字段,mat-select 会突出显示先前的值
- asp.net-mvc - 将 ASP.NET MVC 转换为 ASP.NET Core Razor 页面
- c++ - 如何跳过文件中的名称?
- matlab - 如何在 MATLAB 中为“lsqnonlin”函数解决以下错误
- angular - 有没有办法查看 Angular 的 webpack 配置?