Updating Request Headers in Django Middleware
Before I start complaining about my problem, I have to admit, that I'm not sure if my approach is the best way to handle my problem. I'm using Nuxt as my Frontend and I want to check/renew the JWT access token if it is expired, but the refresh token is still valid.
Hey, I'm currently trying to write a middleware in Django, which is responsible for updating the JWT access token. However, the test says that I'm not authorized, even though I've updated the header.
class JWTRefreshMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request: HttpRequest):
if request.headers.get("Authorization"):
try:
AccessToken(
str(request.headers.get("Authorization")).split(" ")[1], verify=True
)
except TokenError:
if refresh_token_cookie := request.COOKIES.get("refresh_token"):
try:
refresh_token = RefreshToken(refresh_token_cookie, verify=True)
user = CustomUser.objects.get(
id=refresh_token.payload.get("user_id")
)
new_access_token = str(AccessToken.for_user(user))
request.META["HTTP_AUTHORIZATION"] = (
f"Bearer {new_access_token}"
)
except TokenError:
pass
response: HttpResponse = self.get_response(request)
return response
The endpoint which I'm trying to call looks like the following:
from ninja_jwt.authentication import JWTAuth
router = Router()
@router.get("/profile", response={200: UserProfileResponse}, auth=JWTAuth())
def get_user_profile(request):
# Some Code
I've also tried to override request.headers["Authorization"]
, but...
TypeError: 'HttpHeaders' object does not support item assignment