csurf AJAX call - invalid CSRF token

时间:2016-09-01 06:28:57

标签: jquery ajax node.js express csrf

I'm using the express middleware csurf for CSRF protection. If I'm using it with forms, where I put the token into a hidden field, the action behind the routes works. Now I want to make a simple AJAX call but there csurf says its invalid.

AJAX call:

$('.remove').on('click', function () {
    var csrf = $(this).attr('data-csrf');
    $.ajax({
        type: 'DELETE',
        url: '/user/' + $(this).attr('data-id'),
        data: {
            _csrf: csrf
        },
        success: function (data) {
            //.....
        }
    });
});

And the part in the view:

<td class="uk-table-middle">
  <button data-id="{{ _id }}"  data-csrf="{{ csrfToken }}" class="uk-button-link uk-text-large remove">
      <i class="uk-icon-remove"></i>
  </button> 
</td>

And the init from the middleware:

import * as csurf from 'csurf';
// init bodyparse and and and...
app.use(csurf());

2 个答案:

答案 0 :(得分:0)

我不知道在快递中,但通常CSRF令牌在cookie中,所以你需要这两个功能:

 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;
}

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

然后:

var csrftoken = getCookie('csrftoken');
$.ajax({
    url : formURL,
    type: "POST",
    data : postData,
    beforeSend: function(xhr, settings){
        if (!csrfSafeMethod(settings.type)) xhr.setRequestHeader("X-CSRFToken", csrftoken);
    },
    success:function(data, textStatus, jqXHR){

    },
    error: function(jqXHR, textStatus, errorThrown){
        //if fails
    }
});

或者,如果您不想使用jQuery,可以使用XMLHttpRequest来发出AJAX请求:

var csrftoken = getCookie('csrftoken');
var xhr = new XMLHttpRequest();

xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.onload = function(){
     if(xhr.status === 200){
         var response = JSON.parse(xhr.responseText);
         console.log(response)
     }
 };
 xhr.send(encodeURI('category=' + cat));

答案 1 :(得分:0)

此方法无效的唯一原因是您没有使用ajax请求传递Cookie。当我查看代码时,当我弄清楚时,我很挣扎。

Csurf需要您传递存储在Cookie(_csrf)上的密钥。 Cookie通过基于域的权限(允许CORS的服务器除外)具有限制

在我的情况下,我使用fetch传递具有相同域请求的cookie(我不必允许CORS)

const { _csrf, someData } = jsonData; // _csrf here you got from the form
const response = await fetch("/api/some/endpoint", {
  method: "POST",
  credentials: "same-origin", // here is the option to include cookies on this request
  headers: {
    "x-csrf-token": _csrf,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ someData })
});

请注意上面的代码我使用的是es6格式。如果您要求使用其他域名,则可以使用same-origin更改include a.k.a CORS see the doc here

如果您使用jQuery作为库,此代码可能对您有用。此代码未经测试,您应该根据您使用的库自行查找。

 $.ajax({
   url: 'http://your.domain.com/api/some/endpoint',
   xhrFields: { withCredentials: true }, // this include cookies
   headers: {'x-csrf-token': 'YourCSRFKey'}
 })

传递_csrf值时,您可以在标题发布数据查询字符串上自由使用您自己的名称。在上面的示例中,我使用名为x-csrf-token的标头,但您可以使用基于下面的屏幕截图代码的其他方法。

Sample code from csurf when geting _csrf value