没有"Authorization"头,如何访问授权头?姜戈



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

首先我实现了中间件。现在在devtools的网站上(当我发布一些东西时),我看到带有令牌的授权头。

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添加到request header中,而不是添加到response中(Django将返回给客户端):

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

相关内容

  • 没有找到相关文章

最新更新