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

1

5

I wrote in urls:


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'),
    ...
]

Then when I request api/token/, I got a json response with only access and refresh tokens.
But I need to get also an access token expires time for saving it to localStorage and request to the refresh url, save the new access token in the storage if the time was expired

Irruption answered 29/8, 2020 at 15:9 Comment(0)
L
7

I had the same problem. One way to solve this problem is to have new serializers for access and refresh APIs, like:

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

And also add new views for that as well like:

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

and finally add new views to your urls like:

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'),
]

Now despite of those tokens of yours, you also have expire times in both of your APIs.

Labourer answered 30/8, 2020 at 15:2 Comment(1)
do you maybe know how to send a profile_image back with the response?Mckoy

© 2022 - 2024 — McMap. All rights reserved.