首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >没有authorization头部,如何访问authorization头部?姜戈

没有authorization头部,如何访问authorization头部?姜戈
EN

Stack Overflow用户
提问于 2021-10-24 11:27:40
回答 1查看 135关注 0票数 1

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

首先,我实现了中间件。现在在devtools的网站上(当我发布一些东西时),我看到authorizational header with token。

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-24 11:54:36

您正在将标头分配给错误的实体。不是将header添加到响应( Django将返回给客户端的内容),而是将其添加到请求header:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69696276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档