问题描述
我正在尝试使用我的一个视图的TokenAuthentication。
如,我添加了我从登录中收到的令牌,作为HTTP头,在我发送的请求中称为授权。
I'm trying to use the TokenAuthentication with one of my views.As documented in http://django-rest-framework.org/api-guide/authentication.html, I add the token I received from the login as an HTTP header called: 'Authorization' in the request I send.
问题是在我的unittests认证失败。
查看TokenAuthentication类,我看到被检查的头是'HTTP_AUTHORIZATION'而不是'授权'
The problem is that in my unittests the authentication fails.Looking into the TokenAuthentication class I see that the header being checked is 'HTTP_AUTHORIZATION' and not 'Authorization'
我使用的视图:
The view I'm using:
class DeviceCreate(generics.CreateAPIView):
model = Device
serializer_class = DeviceSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
将标题更改为'HTTP_AUTHORIZATION'似乎有效,但有些事情感到错误。
Changing the header to 'HTTP_AUTHORIZATION' seems to work, but something feels wrong.
我没有任何东西?
推荐答案
不正确,在请求 META
dict中进行查找时,其实际查找的标题与之前的 HTTP_
,所以 request.META.get('HTTP_AUTHORIZATION','')
实际查找授权
请求中的头。
Not quite true, when doing lookups in the request META
dict, the headers that it's actually looking for are with out the preceeding HTTP_
, so request.META.get('HTTP_AUTHORIZATION', '')
is actually looking up the Authorization
header in the request.
我没有仔细检查测试客户端的外观,但我相信设置 HTTP_AUTHORIZATION
是您需要做的相当于实际设置授权
标题。如果您实际发出http请求,您应该会发现设置auth标头的工作原理与您预期的一样。
I havn't double checked how the test client looks but I believe that setting HTTP_AUTHORIZATION
is what you need to do get the equivalent of actually setting the Authorization
header. If you actually made an http request you should find that setting the auth header works exactly as you'd expect.
请参阅 request.META
文档:
修改:
Django文档查找 request.META
中的标题:
Django docs on looking up headers in request.META
:
Django文档使用测试客户端设置头文件:
Django docs on setting headers with the test client:
这篇关于Django TokenAuthentication缺少'授权'http头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!