Django rest framework Django rest框架令牌身份验证不起作用

Django rest framework Django rest框架令牌身份验证不起作用,django-rest-framework,token,login-required,Django Rest Framework,Token,Login Required,我试图将json数据发布到url,并用login_required修饰,但django返回重定向到登录页面 DRF设置: 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 以及已安装的应用程序中的rest_framework.authto

我试图将json数据发布到url,并用login_required修饰,但django返回重定向到登录页面

DRF设置:

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.TokenAuthentication',
),
以及已安装的应用程序中的rest_framework.authtoken

我可以通过curl获得auth令牌

$ curl -X POST -d "{\"username\" : 7, \"password\" : 1}" -H "Content-Type: application/json" http://127.0.0.1:9000/extapi/get-auth-token/
{"token":"bc61497d98bed02bd3a84af2235365d0b2b549ff"}
但是,当我发布到视图时(用login_required修饰),django返回HTTP302,位置头指向登录页面

$ curl -v -X POST -d '{"event":"14","user":"7","action":"1868","unit":"","value":"-1"}' -H "Content-Type: application/json" -H "Authorization: Token bc61497d98bed02bd3a84af2235365d0b2b549ff" http://127.0.0.1:9000/zk2015/events/actions/api/uservotejournal/7/
* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 9000 (#0)
> POST /zk2015/events/actions/api/uservotejournal/7/ HTTP/1.1
> User-Agent: curl/7.35.0
> Host: 127.0.0.1:9000
> Accept: */*
> Content-Type: application/json
> Authorization: Token bc61497d98bed02bd3a84af2235365d0b2b549ff
> Content-Length: 64
> 
* upload completely sent off: 64 out of 64 bytes
< HTTP/1.1 302 FOUND
* Server nginx/1.4.6 (Ubuntu) is not blacklisted
< Server: nginx/1.4.6 (Ubuntu)
< Date: Fri, 18 Sep 2015 11:14:31 GMT
< Content-Type: text/html; charset=utf-8
< Location: http://127.0.0.1:9000/accounts/login/?next=/zk2015/events/actions/api/uservotejournal/7/
< Transfer-Encoding: chunked
< Connection: keep-alive
< Vary: Cookie
< X-Frame-Options: SAMEORIGIN
< ETag: "d41d8cd98f00b204e9800998ecf8427e"
< Set-Cookie: csrftoken=G85fWrKKsIA5a2uGPIn9fS4pqKrS51jK; expires=Fri, 16-Sep-2016 11:14:31 GMT; Max-Age=31449600; Path=/
< 
* Connection #0 to host 127.0.0.1 left intact
我曾尝试在rest\u framework.authentication.SessionAuthentication和rest\u framework.authentication.TokenAuthentication中设置断点,但从未触发过


我的设置有什么问题?请提供帮助。

您没有在curl的标题中传递授权

curl -X POST -d "{\"username\" : 7, \"password\" : 1}" -H "Authorization: Token bc61497d98bed02bd3a84af2235365d0b2b549ff" http://127.0.0.1:9000/extapi/get-auth-token/

关键是request.user在drf.APIView.dispatch中是匿名用户,但在drf.APIView.post和其他类似方法中定义为授权用户

这与django不同:request.user在django.views.View.dispatch中定义为授权用户


这也是为什么django.contrib.auth.decorators.login_required与drf视图不兼容的原因。

引用的请求是为了获取auth令牌,我无法将其发布到那里。