【问题标题】:Django: CSRF verification failed. Request abortedDjango:CSRF 验证失败。请求中止
【发布时间】:2016-05-11 19:09:39
【问题描述】:

调用的视图函数是这样的

def parsing(request):
    url = request.POST['url']
    ...
    return HttpResponse(json.dumps(resultDict))

当我通过以下代码向它发出 post 请求时,

import requests
url = 'http://tv.cntv.cn/video/C12278/a7ea7c0e810b4701bf1d3f5254b8a26a'
c = requests.post("http://127.0.0.1:8000/VideoParser/", data={'url': url})
print(c.text)

然后请求失败,它只是给出以下HTML代码,

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="robots" content="NONE,NOARCHIVE">
  <title>403 Forbidden</title>
  <style type="text/css">
    html * { padding:0; margin:0; }
    body * { padding:10px 20px; }
    body * * { padding:0; }
    body { font:small sans-serif; background:#eee; }
    body>div { border-bottom:1px solid #ddd; }
    h1 { font-weight:normal; margin-bottom:.4em; }
    h1 span { font-size:60%; color:#666; font-weight:normal; }
    #info { background:#f6f6f6; }
    #info ul { margin: 0.5em 4em; }
    #info p, #summary p { padding-top:10px; }
    #summary { background: #ffc; }
    #explanation { background:#eee; border-bottom: 0px none; }
  </style>
</head>
<body>
<div id="summary">
  <h1>Forbidden <span>(403)</span></h1>
  <p>CSRF verification failed. Request aborted.</p>


  <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie 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 cookies, please re-enable them, at least for this site, or for &#39;same-origin&#39; requests.</p>

</div>

<div id="info">
  <h2>Help</h2>
    
    <p>Reason given for failure:</p>
    <pre>
    CSRF cookie not set.
    </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.9/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>

  <p>You're seeing the help section of this page because you have <code>DEBUG =
  True</code> in your Django settings file. Change that to <code>False</code>,
  and only the initial error message will be displayed.  </p>

  <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>
</div>

</body>
</html>

看来失败的原因是

CSRF cookie 未设置。

但是,我的应用在整个过程中没有明确涉及任何cookie和模板,任何人都可以帮助解决问题吗?我只是 Django 初学者。

【问题讨论】:

  • 只需一个简单的csrf_exempt 装饰器就可以完成这项工作。请参阅下面的答案。

标签: python django python-3.x cookies


【解决方案1】:

您可以使用csrf_exempt 装饰器作为您的视图:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def parsing(request):
    url = request.POST['url']
    ...
    return HttpResponse(json.dumps(resultDict))

来自文档:

此装饰器将视图标记为不受保护 由中间件保证。

你可以阅读更多关于csrf保护here

【讨论】:

    【解决方案2】:

    您正在使用 POST 请求,该请求通过请求令牌再次受到 CSRF 攻击的保护。

    您可以在 Django 文档中阅读有关 CSRF 令牌的更多信息:https://docs.djangoproject.com/en/1.9/ref/csrf/

    【讨论】:

      【解决方案3】:

      这个问题你有两个选择

      首先:-

      如果您想使用 csrf 身份验证,您必须在来自前端的每个请求中添加 cookie,因为您需要在前端代码中添加以下 sniipet

      function getCookie(name) {
          var cookieValue = null;
          if (document.cookie && document.cookie != '') {
              var cookies = document.cookie.split(';');
              for (var i = 0; i < cookies.length; i++) {
                  var cookie = jQuery.trim(cookies[i]);
                  // Does this cookie string begin with the name we want?
                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                      break;
                  }
              }
          }
          return cookieValue;
      }
      var csrftoken = getCookie('csrftoken');
      

      并在您的 Ajax 调用或 Angular 服务中将此 csrftoken 作为标头传递。

      第二个:-

      如果您遇到交叉标头错误,如果它拒绝您对 django 服务器的请求,那么只需执行 pip install django-cors-headers 并修改 settings.py 与

      INSTALLED_APPS = (
          ...
          'corsheaders',
          ...
      )
      
      
      MIDDLEWARE_CLASSES = (
          ...
          'corsheaders.middleware.CorsMiddleware',
          'django.middleware.common.CommonMiddleware',
          ...
      )
      

      希望对你有帮助!!

      【讨论】:

        【解决方案4】:

        只需从您的 settings.py 中的 MIDDLEWARE_CLASSES 中删除“django.middleware.csrf.CsrfViewMiddleware”

        【讨论】:

        • 我相信从中间件中删除 django.middleware.csrf.CsrfViewMiddleware 是不明智的。这就是 csrf_exempt 装饰器的含义。
        猜你喜欢
        • 1970-01-01
        • 2012-05-10
        • 2017-06-17
        • 2016-04-15
        • 2012-12-07
        • 2015-03-08
        • 1970-01-01
        • 2016-08-27
        相关资源
        最近更新 更多