【问题标题】:Django-rest-framework token auth doesn't workDjango-rest-framework 令牌身份验证不起作用
【发布时间】:2015-12-15 12:39:47
【问题描述】:

我正在尝试将 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 中设置断点,但它们从未被解雇

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

【问题讨论】:

    标签: django-rest-framework token login-required


    【解决方案1】:

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

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

    【讨论】:

    • 引用的请求是获取身份验证令牌,我不能在那里发布。
    【解决方案2】:

    重点是drf.APIView.dispatch()中request.user是AnonymousUser,而drf.APIView.post()等类似方法中定义为授权用户。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 2019-01-18
      • 2020-09-12
      • 2019-05-18
      • 2019-02-20
      • 2021-07-01
      • 2018-03-25
      相关资源
      最近更新 更多