我的Django网站是HTTPS。当我试图从脚本向网站发布数据时,我得到了这个错误:“引用检查失败-没有引用”。这似乎是一个CSRF的问题,但我不知道如何解决它。
示例:
import requests
r = requests.post('https://mywebsite/mypage', data = {'key':'value'})
print r.text给出了以下输出:
[...]
<p>Reason given for failure:</p>
<pre>
Referer checking failed - no Referer.
</pre>
<p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
<a
href="https://docs.djangoproject.com/en/1.8/ref/csrf/">Django's
CSRF mechanism</a> has not been used correctly. For POST forms, you need to
ensure:</p>
<ul>
<li>Your browser is accepting cookies.</li>
<li>The view function passes a <code>request</code> to the template's <a
href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a>
method.</li>
<li>In the template, there is a <code>{% csrf_token
%}</code> template tag inside each POST form that
targets an internal URL.</li>
<li>If you are not using <code>CsrfViewMiddleware</code>, then you must use
<code>csrf_protect</code> on any views that use the <code>csrf_token</code>
template tag, as well as those that accept the POST data.</li>
</ul>
[...]在发送POST数据之前,我需要将引用传递给我的标头吗?这不太方便?或者我应该禁用此页面的CSRF?
谢谢
发布于 2016-04-16 01:24:14
AFAIK,这是CSRF的目的,以避免发布来自未知奇怪来源的数据。你需要csrf令牌来发布这个django动态生成的代码。
发布于 2022-02-09 12:08:22
升级Django可能会修复缺少Referer的错误。
从Django 4.0 (release notes)开始,后台会先检查Origin header,再回退到Referer header (source):
如果浏览器提供了原点标头,
CsrfViewMiddleware将根据当前主机和CSRF_TRUSTED_ORIGINS设置验证原点标头。这提供了对跨子域攻击的保护。Origin请求,如果没有提供HTTPS头部,CsrfViewMiddleware将执行严格的引用检查。这意味着即使子域可以在您的域上设置或修改cookies,它也不能强制用户发布到您的应用程序,因为该请求不会来自您自己的确切域。https://stackoverflow.com/questions/36651856
复制相似问题