首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django CSRF验证POST请求失败: referer检查失败-没有Referer

Django CSRF验证POST请求失败: referer检查失败-没有Referer
EN

Stack Overflow用户
提问于 2016-04-16 00:01:01
回答 2查看 2.5K关注 0票数 3

我的Django网站是HTTPS。当我试图从脚本向网站发布数据时,我得到了这个错误:“引用检查失败-没有引用”。这似乎是一个CSRF的问题,但我不知道如何解决它。

示例:

代码语言:javascript
复制
import requests
r = requests.post('https://mywebsite/mypage', data = {'key':'value'})
print r.text

给出了以下输出:

代码语言:javascript
复制
[...]

<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?

谢谢

EN

回答 2

Stack Overflow用户

发布于 2016-04-16 01:24:14

AFAIK,这是CSRF的目的,以避免发布来自未知奇怪来源的数据。你需要csrf令牌来发布这个django动态生成的代码。

票数 3
EN

Stack Overflow用户

发布于 2022-02-09 12:08:22

升级Django可能会修复缺少Referer的错误。

从Django 4.0 (release notes)开始,后台会先检查Origin header,再回退到Referer header (source):

如果浏览器提供了原点标头,

  1. CsrfViewMiddleware将根据当前主机和CSRF_TRUSTED_ORIGINS设置验证原点标头。这提供了对跨子域攻击的保护。
  2. 另外,对于Origin请求,如果没有提供HTTPS头部,CsrfViewMiddleware将执行严格的引用检查。这意味着即使子域可以在您的域上设置或修改cookies,它也不能强制用户发布到您的应用程序,因为该请求不会来自您自己的确切域。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36651856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档