jQuery 将 CSRF 令牌添加到所有 $.post() 请求的数据 [英] jQuery add CSRF token to all $.post() requests' data

查看:41
本文介绍了jQuery 将 CSRF 令牌添加到所有 $.post() 请求的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Laravel 5 应用程序,该应用程序默认为所有 POST 请求启用 CSRF 保护.我喜欢这种增加的安全性,所以我正在尝试使用它.

I am working on a Laravel 5 app that has CSRF protection enabled by default for all POST requests. I like this added security so I am trying to work with it.

在发出一个简单的 $.post() 请求时,我收到了一个 'IlluminateSessionTokenMismatchException' 错误,因为所需的表单输入 _token 从 POST 数据中丢失.这是有问题的 $.post 请求的示例:

While making a simple $.post() request I received a 'IlluminateSessionTokenMismatchException' error because the required form input _token was missing from the POST data. Here is an example of a $.post request in question:

var userID = $("#userID").val();
$.post('/admin/users/delete-user', {id:userID}, function() {
// User deleted
});

我将我的 CSRF 令牌作为元字段存储在我的标头中,并且可以使用以下方法轻松访问它:

I have my CSRF token stored as a meta field in my header and can easily access it using:

var csrf_token = $('meta[name="csrf-token"]').attr('content');

是否可以将其附加到所有传出 $.post() 请求的 json 数据中?我尝试使用标题,但 Laravel 似乎无法识别它们 -

Is it possible to append this to the json data on all outgoing $.post() requests? I tried using headers but Laravel did not seem to recognize them -

var csrf_token = $('meta[name="csrf-token"]').attr('content');
alert(csrf_token);
$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    if (options['type'].toLowerCase() === "post") {
        jqXHR.setRequestHeader('X-CSRFToken', csrf_token);
    }
});

推荐答案

您的 $.ajaxPrefilter 方法是一种很好的方法.不过,您不需要添加标题;您只需要向 data 字符串添加一个属性.

Your $.ajaxPrefilter approach is a good one. You don't need to add a header, though; you simply need to add a property to the data string.

数据作为 $.post 的第二个参数提供,然后格式化为查询字符串 (id=foo&bar=baz&...)在预过滤器访问 data 选项之前.因此,您需要将自己的字段添加到查询字符串中:

Data is provided as the the second argument to $.post, and then formatted as a query string (id=foo&bar=baz&...) before the prefilter gets access to the data option. Thus, you need to add your own field to the query string:

var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    if (options.type.toLowerCase() === "post") {
        // initialize `data` to empty string if it does not exist
        options.data = options.data || "";

        // add leading ampersand if `data` is non-empty
        options.data += options.data?"&":"";

        // add _token entry
        options.data += "_token=" + encodeURIComponent(csrf_token);
    }
});

这会将 id=userID 变成 id=userID&_token=csrf_token.

这篇关于jQuery 将 CSRF 令牌添加到所有 $.post() 请求的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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