I have created a custom django middleware and decorator to authenticate the RESTful API that I am developing. Here is the code of the middleware that I have developed:
# myproject/middleware.py
import jwt
from django.conf import settings
from django.http import JsonResponse
from users.models import User
class JWTAuthenticationMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
excluded_paths = ['/auth/users/register/', '/auth/users/login/']
if any(request.path.startswith(path) for path in excluded_paths):
return self.get_response(request) # Skip JWT validation for excluded paths
token = request.COOKIES.get('jwt')
if token:
try:
decoded = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
user = User.objects.get(id=decoded['id'])
request.user = user
except (jwt.ExpiredSignatureError, jwt.InvalidTokenError, User.DoesNotExist):
return JsonResponse({'error': 'Invalid or expired token'}, status=401)
else:
request.user = None
return self.get_response(request)
This is the code for the decorator:
# users/utils.py
from functools import wraps
from django.http import JsonResponse
from django.middleware.csrf import CsrfViewMiddleware
def token_required(view_func):
@wraps(view_func)
def _wrapped_view(view_class_instance, request, *args, **kwargs):
csrf_middleware = CsrfViewMiddleware()
# Check CSRF token
csrf_error = csrf_middleware.process_view(request, None, (), {})
if csrf_error:
return csrf_error
if not request.user:
return JsonResponse({'error': 'Token is missing or invalid'}, status=401)
return view_func(view_class_instance, request, *args, **kwargs)
return _wrapped_view
Here is one of the views that are giving the error:
from rest_framework.views import APIView
from users.serializers import UserSerializer
from rest_framework.response import Response
from users.models import User
from rest_framework.exceptions import AuthenticationFailed
import jwt
from django.conf import settings
from users.utils import token_required
class UserView(APIView):
@token_required
def get(self, request):
token = request.COOKIES.get('jwt')
if not token:
raise AuthenticationFailed('Unauthenticated User!')
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise AuthenticationFailed("Token has expired! Login again")
user = User.objects.filter(id=payload['id']).first()
serializer = UserSerializer(user)
return Response(serializer.data)
And the error is this:
MiddlewareMixin.init() missing 1 required positional argument: ‘get_response’
I really need help with getting this to work. Versions of Python and Django that I am using are 3.12.3 and 5.0.4 respectively.
I have tried many different solutions but none worked so far. Even ChatGPT isn’t able to find the issues in this small piece of code.
Bilal Tufail is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.