csurf AJAX调用 - 无效的CSRF令牌 [英] csurf AJAX call - invalid CSRF token

查看:123
本文介绍了csurf AJAX调用 - 无效的CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用快速中间件csurf进行CSRF保护。如果我将它与表单一起使用,我将令牌放入隐藏字段,路由背后的操作就可以了。现在我想做一个简单的AJAX调用,但csurf说它无效。



AJAX调用:

  $('。remove')。on('click',function(){
var csrf = $(this).attr('data- csrf');
$ .ajax({
类型:'DELETE',
url:'/ user /'+ $(this).attr('data-id'),
数据:{
_csrf:csrf
},
成功:函数(数据){
// .....
}
});
});

视图中的部分:

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

来自中间件的init:

 从'csurf'导入*为csurf; 
// init bodyparse and和...
app.use(csurf());


解决方案

此方法不起作用的唯一原因是你没有用你的ajax请求传递cookie。当我查看代码时,当我弄清楚时,我很挣扎。



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



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

  const {_csrf,someData } = jsonData; // _csrf这里你从形式
const response = await fetch(/ api / some / endpoint,{
method:POST,
凭证:same-origin) ,//这里是在此请求中包含cookie的选项
标题:{
x-csrf-token:_csrf,
Content-Type:application / json
},
body:JSON.stringify({someData})
});

请注意上面的代码我使用的是es6格式。如果您请求不同的域名为CORS


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

解决方案

The only reason why this method doesn't work is that you're not passing cookies with your ajax request. I was struggling when I figuring it out when I look into the code.

Csurf needs you to pass the secret key which stored on cookies (_csrf). Cookies have a limitation through the permission based on the domain (except your server allowing CORS)

On my case, I use fetch to passing the cookies with same domain request (i don't have to allow 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 })
});

Please note the code above I'm using es6 format. You may change same-origin with include if you requesting to different domain a.k.a CORS see the doc here

If you using jQuery as the library, this code could be useful to you. This code was untested and you should find out by yourself based on what library you use.

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

Please be free to use your own names on the headers, post data or querystring when passing the _csrf value. On my example above I'm using header with name x-csrf-token, but you can use other method based on screenshot code below.

这篇关于csurf AJAX调用 - 无效的CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆