1

如何获取 jwt 令牌过期时间或发布时间,在 Django REST 框架简单的 jwt 库中。我需要传递令牌到期时间以响应客户端。

4

1 回答 1

1

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
于 2020-10-07T09:21:19.797 回答