1👍
YOu should not use the MiddlewareMixin
, the MiddlewareMixin
is for the old-style middleware, but you are writing this in the new way, so:
class TokenMiddleware: # !L! no MiddlewareMixin
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
authorization = request.META.get('HTTP_AUTHORIZATION')
if authorization and authorization.startswith('Bearer '):
token = authorization.split(' ')[1]
jwks_client = jwt.PyJWKClient(settings.JWT_VERIFY_URL)
header = jwt.get_unverified_header(token)
key = jwks_client.get_signing_key(header['kid']).key
try:
jwt.decode(token, key, [header['alg']])
except jwt.ExpiredSignatureError:
return JsonResponse({'error': 'Token has expired'}, status=401)
except jwt.DecodeError:
return JsonResponse({'error': 'Token is invalid'}, status=401)
else:
return JsonResponse(
{'message': 'Authentication Bearer Token is required.'}
)
return self.get_response(request)
As for the DRF, your TokenMiddleware
is not an authentication class, but likely not necessary here anyway, since it will go through the middleware. You thus remove this from the AUTHENTICATION_CLASSES
:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
# 'my_app.middleware.TokenMiddleware', # 🖘 remove
],
# …
}
0👍
I see configuration you shown indicates that you added TokenMiddleware both to the MIDDLEWARE and REST_FRAMEWORK[‘DEFAULT_AUTHENTICATION_CLASSES’]. This is the problem.
If TokenMiddleware is supposed to be middleware:
Remove ‘my_app.middleware.TokenMiddleware’ from the DEFAULT_AUTHENTICATION_CLASSES in REST_FRAMEWORK.
If TokenMiddleware is supposed to be an authentication class:
Remove ‘my_app.middleware.TokenMiddleware’ from the MIDDLEWARE.