没有"Authorization"header,如何获取权限header?姜戈

No "Authorization" header, how to access authorization header? Django

我需要检查每个传入请求的授权 HTTP Header。

首先我实现了中间件。现在在 devtools 的网站上(当我 post 时)我看到授权 header 和令牌。

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)

您将 header 分配给了错误的实体。而不是将 header 添加到响应(Django 将 return 返回给客户端),您需要将其添加到请求 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