1
from datetime import datetime, timezone
from rest_framework_simplejwt.tokens import RefreshToken
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

class TokenRefreshMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        if response.status_code == 200:
            refresh_token = request.COOKIES.get('refresh_token')
            if refresh_token:
                try:
                    decoded = RefreshToken(refresh_token, verify=False)
                    if decoded:
                        if decoded.access_token['exp'] < datetime.datetime.now(timezone.utc).timestamp():
                            refresh = RefreshToken(refresh_token)
                            response.set_cookie('access_token', refresh.access_token)
                            response.set_cookie('refresh_token', refresh)
                except:
                    pass
        if response.status_code == 401:
            refresh_token = request.COOKIES.get('refresh_token')
            if refresh_token:
                print ("refresh_token = = = = = ", refresh_token)
                try:
                    decoded = RefreshToken(refresh_token, verify=False)
                    if decoded:
                            refresh = RefreshToken(refresh_token)
                            response.set_cookie('access_token', refresh.access_token)
                            response.set_cookie('refresh_token', refresh)
                            response.status_code = 200
                            
                except:
                    pass
        return response
    

hello I m working on the authentication using django (dj-rest-auth), I use httpOnly cookie to store the access token and refresh token so I don't have access to them in the front end, which means I must handle that in the backend, I wrote this middleware to keep refreshing the access token but whenever it is expired I get the response below:

{ "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } until I reload the page for the second time then the authenticated user shows up

Bif_Titan
  • 11
  • 1
  • That seems right, you refresh the token when sending the response (*The response is already `Token is invalid or expired` at that point*) so the refreshed token is used at the next request. Try checking the token in the request before the token is "consumed" by whatever is using it. – Daviid Aug 01 '23 at 11:32
  • I did that but still need to reload the page in order to (the refresh token process) take effect – Bif_Titan Aug 02 '23 at 13:56

0 Answers0