我正在提供一个API,可以使用小型传感器发送带有数据的POST请求。该传感器具有有限的软件,我想在我的API视图上禁用CSRF保护。
所以我添加了装饰器:
url(
regex=r'^beacons/$',
view=csrf_exempt(ScanListCreateAPIView.as_view()),
name='beacons'
),
不幸的是,当我使用传感器执行POST时,仍然会收到403错误:
<h1>Forbidden <span>(403)</span></h1>
<p>CSRF verification failed. Request aborted.</p>
<p>You are seeing this message because this HTTPS site requires a 'Referer
header' to be sent by your Web browser, but none was sent
. This header is
required for security reasons, to ensure that your browser is not being
hijacked by third parties.</p>
<p>If you have configured your browser to disable 'Referer' headers, please
re-enable them, at least for this site, or for HTTPS connections, or for
'same-origin' requests.</p>
我尝试在POST请求中添加“Referer:”null标头,但我仍然有403响应,提到CSRF失败。
我的要求是:
POST /api/beacons HTTP/1.1
Host: vincent.pythonanywhere.com
Content-Type: application/json
Accept: */*
User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)
Content-Length: 597
{"beacon":"aaa"," ...
通过curl传递的相同请求正常,201响应。
答案 0 :(得分:0)
以下是diable CSRF的解决方案:
1-由于DRF使用SessionAuth执行自己的csrf,您必须在视图中指定:
authentication_classes = (BasicAuthentication,)
2-然后我不知道为什么,但网址中的view=csrf_exempt(ScanListCreateAPIView.as_view()),
不起作用。相反,使用大括号mixin:
from braces.views import LoginRequiredMixin, CsrfExemptMixin
class ScanListCreateAPIView(ListCreateAPIView, CsrfExemptMixin):
authentication_classes = (BasicAuthentication,)