gpt4 book ai didi

django - Django TokenAuthentication缺少 'Authorization' http header

转载 作者:行者123 更新时间:2023-12-03 14:45:42 24 4
gpt4 key购买 nike

我正在尝试将TokenAuthentication与我的一种 View 一起使用。
https://www.django-rest-framework.org/api-guide/authentication/中所述,我在发送的请求中添加了从登录名中收到的 token ,并将其作为HTTP header 添加为“Authorization”。

问题是在我的单元测试中,身份验证失败。
查看TokenAuthentication类,我看到要检查的 header 是“HTTP_AUTHORIZATION”而不是“Authorization”

我正在使用的 View :

class DeviceCreate(generics.CreateAPIView):
model = Device
serializer_class = DeviceSerializer

authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)

将 header 更改为“HTTP_AUTHORIZATION”似乎可行,但感觉有些错误。

我有什么想念的吗?

最佳答案

Looking into the TokenAuthentication class I see that the header being checked is 'HTTP_AUTHORIZATION' and not 'Authorization'



并非完全正确,当在请求 META字典中进行查找时,它实际寻找的 header 没有前面的 HTTP_,因此 request.META.get('HTTP_AUTHORIZATION', '')实际上是在请求中查找 Authorization header 。

The problem is that in my unittests the authentication fails Changing the header to 'HTTP_AUTHORIZATION' seems to work



我没有仔细检查测试客户端的外观,但我相信设置 HTTP_AUTHORIZATION是您需要做的,等同于实际设置 Authorization header 。如果您实际上发出了http请求,则应该发现设置auth header 的工作与您期望的完全一样。

请在此处查看 request.META文档: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META

编辑:

有关在 request.META中查找 header 的Django文档:

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.



有关使用测试客户端设置 header 的Django文档:

However, you can use keywords arguments to specify some default headers. For example, this will send a User-Agent HTTP header in each request:

c = Client(HTTP_USER_AGENT='Mozilla/5.0')

关于django - Django TokenAuthentication缺少 'Authorization' http header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15113248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com