1

I need to check the Authorization HTTP Header of every incoming request.

First i have implemented Middleware. Now on website in devtools (when i post something) i see authorizational header with token.

class MyMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        user_id = request.POST.get('created_by', False)
        try:
            api_token = CustomUser.objects.get(user=user_id).api_token

        except MyUser.DoesNotExist:
            api_token = ''
        response = self.get_response(request)
        response['Authorization'] = "Bearer " + api_token

        return response



class MyApiView(mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = Event.objects.all()
    serializer_class = EventSerializer
    @action(methods=['POST'], detail=False)
    def post(self, request):
        print(request.META['HTTP_AUTHORIZATION']) **#keyerror**
        print(request.META['Authorization']) **#keyerror**
        print(request.headers.items()) **#no authorization header**
        tutorial_serializer = MyApiSerializer(data=request.data)
        if tutorial_serializer.is_valid():
            tutorial_serializer.save()
            return Response(tut`enter code here`orial_serializer.data, status=status.HTTP_201_CREATED)
        return Response(tutorial_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
J maria
  • 373
  • 1
  • 8

1 Answers1

1

You're assigning header to wrong entity. Instead of adding header to response (what Django will return back to client), you need to add it to request headers:

from django.utils.deprecation import MiddlewareMixin


class CustomHeaderMiddleware(MiddlewareMixin):

    def process_request(self, request):
        user_id = request.POST.get('created_by', False)
        try:
            api_token = CustomUser.objects.get(user=user_id).api_token
        except CustomUser.DoesNotExist:
            api_token = ''
        request.META['HTTP_Authorization'] = "Bearer " + api_token
        response = self.get_response(request)
        return response
Charnel
  • 4,222
  • 2
  • 16
  • 28