2

我正在尝试将 json 数据发布到 url,用 login_required 装饰,但 django 返回重定向到登录页面

DRF 设置:

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.TokenAuthentication',
),

并且rest_framework.authtokenINSTALLED_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 中设置断点,但它们从未被解雇

我的设置有什么问题?请帮忙。

4

2 回答 2

2

您没有在 curl 的 Header 中传递授权

curl -X POST -d "{\"username\" : 7, \"password\" : 1}" -H "Authorization: Token bc61497d98bed02bd3a84af2235365d0b2b549ff" http://127.0.0.1:9000/extapi/get-auth-token/
于 2015-09-18T12:36:11.770 回答
2

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

这与 django 不同:request.user 被定义为授权用户django.views.View.dispatch()

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

于 2015-09-18T13:09:46.950 回答