Home > Enterprise >  No "Authorization" header, how to access authorization header? Django
No "Authorization" header, how to access authorization header? Django

Time:10-25

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 CustomUser.DoesNotExist:
            api_token = ''
        response = self.get_response(request)
        response['Authorization'] = "Bearer "   api_token

        return response

and now im trying to access Authorization HTTP Header of every incoming request to validate it but there is no Authorization Header

class EventApiView(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 = EventSerializer(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)

CodePudding user response:

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
  • Related