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