简体   繁体   English

Django给出“ CSRF令牌丢失或不正确”。 即使在POST调用中传递了错误之后

[英]Django gives 'CSRF token missing or incorrect.' error even after passing it in the POST call

I have a django application that is successfully able to signup and login a user.However I am unable to logout a user. 我有一个django应用程序,可以成功注册和登录用户。但是我无法注销用户。

In the front end, I have a webpage that contains a power button icon, which on clicking should trigger a logout request. 在前端,我有一个网页,其中包含一个电源按钮图标,单击该图标将触发注销请求。

I am using angular js for front end 我在前端使用angular js

index.html 的index.html

<div class="col-xs-2">
     <span style="opacity: 0.5;font-family: FontAwesome;font-size: 14px;color:#838F98;text-align:center;cursor:pointer" ng-click="logout()">
               <i class="fa fa-power-off" aria-hidden="true"></i>
     </span>
</div>

Here I use ngclick to call the logout() function that is defined in my index.js 在这里,我使用ngclick调用在index.js中定义的logout()函数

index.js index.js

$scope.logout = function() {
       var url = '/logout';
       var toSend = {
          csrfmiddlewaretoken: '{{ csrf_token }}'
     }
   $http({
      method: 'POST',
      url: url,
      data: toSend,
   }).then(function(response) {
     response.data;
   })
  };

This function calls the /logout url for which I have defined an auth views in urls.py 此函数调用我在urls.py中定义了auth views/logout URL

urls.py urls.py

from django.contrib.auth.views import login, logout

url(r'^logout$', logout, {'template_name': 'login.html'}),

But when I click the power icon on the webpage, I get a 403 Forbidden error.It says CSRF verification failed. Request aborted 但是当我单击网页上的电源图标时,出现403 Forbidden ,表示CSRF verification failed. Request aborted CSRF verification failed. Request aborted .But I am passing the csrf token in the javascript POST call. CSRF verification failed. Request aborted 。但是我在javascript POST调用中传递了csrf令牌。

What am I doing wrong? 我究竟做错了什么?

Make sure to add the csrf token to the http request header in your config module as follow. 确保将csrf令牌添加到配置模块中的http请求标头中,如下所示。

function config($httpProvider) {
    // state provider code

    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}

Also check that your django settings do not have: 还要检查您的django设置是否没有:

CSRF_COOKIE_HTTPONLY=True

CSRF_COOKIE_HTTPONLY default is False but when True, client-side JavaScript will not to be able to access the CSRF cookie. CSRF_COOKIE_HTTPONLY的默认值为False,但为True时,客户端JavaScript将无法访问CSRF cookie。 Read more about this here 在这里阅读更多关于此的信息

When I get those errors is because the csrf token is not in the html form, this is a Django template tag , add it to your html template and then get the actual token by JavaScript to use it with angular The token will be hidden so inspect the html with your browser to see it to confirm that it works, the way you have it setup won't work because you are passing a string of a template tag, Django is supposed to execute that tag in the html before you can captures it with JavaScript from your html tag and then you can post it to your view 当我得到这些错误是因为csrf令牌不在html表单中时,这是Django模板标签,将其添加到html模板中,然后通过JavaScript获取实际的令牌以将它与angular一起使用。令牌将被隐藏,因此请检查用您的浏览器查看html以确认它是否可以正常工作,因此设置方法将不起作用,因为您正在传递模板标签的字符串,Django应该先在html中执行该标签,然后才能捕获它使用HTML标签中的JavaScript,然后可以将其发布到视图中

<div class="col-xs-2">
{{ csrf_token }}
     <span style="opacity: 0.5;font-family: FontAwesome;font-size: 14px;color:#838F98;text-align:center;cursor:pointer" ng-click="logout()">
               <i class="fa fa-power-off" aria-hidden="true"></i>
     </span>
</div>

Instead of passing CSRF Token at each AJAX call (which seems to be a headache and adds to the data array passed) you could make a function in jquery to save the CSRF token as a cookie. 您可以在jquery中创建一个函数将CSRF令牌另存为cookie,而不是在每次AJAX调用时都传递CSRF令牌(这似乎很麻烦,并添加到传递的数据数组中)

Refer the docs . 请参阅文档

Create a file "csrf_ajax.js" (or something of your choice) paste this in it. 创建一个文件“ csrf_ajax.js”(或您选择的东西),将其粘贴到其中。

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');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

Load the script using static files or relative reference 使用静态文件或相对引用加载脚本

Now you can make an AJAX call over POST request without worrying about the CSRF token. 现在,您可以通过POST请求进行AJAX调用,而不必担心CSRF令牌。

Hope this helps you. 希望这对您有所帮助。 Cheers 干杯

Kudos :) 荣誉:)

You can try this : 您可以尝试以下方法:

Step1: Add django-cors-headers 步骤1:添加django-cors-headers

setting.py
-----------
CORS_ALLOW_HEADERS = (
'x-requested-with',
'content-type',
'accept',
'origin',
'authorization',
'X-CSRFToken'
)

Add decorator in view 在视图中添加装饰器

view.py
-------
from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def post(request):
    ## your logic

AngularJS Client side (add token to the request header) AngularJS客户端(将令牌添加到请求标头)

$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;

You can follow this link 您可以点击此链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Django 中的 ajax POST 期间禁止(CSRF 令牌丢失或不正确。) - Forbidden (CSRF token missing or incorrect.) during ajax POST in Django 禁止(CSRF令牌丢失或不正确。)-即使已包含 - Forbidden (CSRF token missing or incorrect.) - even though it's included (缺少CSRF令牌或不正确。)在Django中使用AJAX - (CSRF token missing or incorrect.) using AJAX in Django “禁止(CSRF 令牌丢失或不正确。):”使用 Django 和 JS - “Forbidden (CSRF token missing or incorrect.):” using Django and JS 禁止(CSRF 令牌丢失或不正确。) | Django 和 AJAX - Forbidden (CSRF token missing or incorrect.) | Django and AJAX Django 和 Axios 禁止访问(CSRF 令牌丢失或不正确。) - Django and Axios Forbidden (CSRF token missing or incorrect.) 错误:使用 django rest 框架时禁止(CSRF 令牌丢失或不正确。) - Error :Forbidden (CSRF token missing or incorrect.) while using django rest framework 如何更正 django 中的以下代码,它给出错误“禁止(CSRF 令牌丢失或不正确。)” - How do I correct the following code in django, It's give an error “Forbidden (CSRF token missing or incorrect.)” 尽管我在表单中有 csrf 令牌,但在 Django POST 请求中,禁止的 CSRF 令牌丢失或不正确 - Forbidden CSRF token missing or incorrect in Django POST request even though I have csrf token in form 详细信息:“CSRF失败:CSRF令牌丢失或不正确。” - detail: “CSRF Failed: CSRF token missing or incorrect.”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM