Django-rest-framework令牌认证不起作用

时间:2015-09-18 11:19:52

标签: 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.authtoken

INSTALLED_APPS

我可以通过curl

获取身份验证令牌
$ 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"}

但是当我向视图发布POST时,用login_required修饰,django返回http 302,其中Location标题指向登录页面。

$ 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_framework.authentication.SessionAuthentication和rest_framework.authentication.TokenAuthentication中设置断点,但它们从未被解雇

我的设置有什么问题?求助。

2 个答案:

答案 0 :(得分:2)

您没有在curl中传递Header中的Authorization

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

答案 1 :(得分:2)

关键是request.user是drf.APIView.dispatch()中的AnonymousUser,但在drf.APIView.post()和其他类似方法中被定义为授权用户。

这与django不同:request.user在django.views.View.dispatch()

中被定义为授权用户

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