DRF 简单的 jwt.如何更改 TokenObtainPairView 的响应以获取访问令牌过期时间

DRF simple jwt. How to change response from TokenObtainPairView to get an access token EXPIRES time

我在 url 中写道:


from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    ...
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    ...
]

然后当我请求 api/token/ 时,我得到了一个 json 响应,只有 访问和刷新 令牌。
但我还需要获得一个 访问令牌过期时间 以将其保存到 localStorage 并请求刷新 url,如果时间过期则将新的访问令牌保存在存储中

我遇到了同样的问题。解决此问题的一种方法是为访问和刷新 API 使用新的序列化程序,例如:

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenRefreshSerializer

from rest_framework_simplejwt.tokens import RefreshToken

class TokenObtainLifetimeSerializer(TokenObtainPairSerializer):

    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = self.get_token(self.user)
        data['lifetime'] = int(refresh.access_token.lifetime.total_seconds())
        return data


class TokenRefreshLifetimeSerializer(TokenRefreshSerializer):

    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = RefreshToken(attrs['refresh'])
        data['lifetime'] = int(refresh.access_token.lifetime.total_seconds())
        return data

并为此添加新视图,例如:

from rest_framework_simplejwt.views import TokenViewBase
from accounts.api.serializers import TokenObtainLifetimeSerializer, TokenRefreshLifetimeSerializer


class TokenObtainPairView(TokenViewBase):
    """
        Return JWT tokens (access and refresh) for specific user based on username and password.
    """
    serializer_class = TokenObtainLifetimeSerializer


class TokenRefreshView(TokenViewBase):
    """
        Renew tokens (access and refresh) with new expire time based on specific user's access token.
    """
    serializer_class = TokenRefreshLifetimeSerializer

最后向您的网址添加新视图,例如:

from django.urls import path

from accounts.api.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
    path('token/obtain/', TokenObtainPairView.as_view(), name='token-obtain'),
    path('token/refresh/', TokenRefreshView.as_view(), name='token-refresh'),
]

现在,尽管您有这些令牌,但您的两个 API 也都有过期时间。