jQuery的添加CSRF令牌的所有$。员额()请求“数据 [英] jQuery add CSRF token to all $.post() requests' data
问题描述
我工作的一个Laravel 5应用程序,具有在默认情况下启用所有的POST请求的CSRF保护。我喜欢这增加了安全性,所以我想用它来工作。
同时使我获得了'照亮\会议\ TokenMismatchException
错误一个简单的 $。员额()
请求因为所需的表单输入 _token
中缺少POST数据。这里是一个问题$。员额要求的一个例子:
VAR用户ID = $(#用户ID)VAL()。
.post的$('/管理/用户/删除用户',{ID:用户ID},函数(){
//用户已删除
});
我有我的CSRF令牌存储在我的头一元字段,可以很容易地通过访问它:
VAR csrf_token = $('元[NAME =CSRF令牌])ATTR(内容)。
是否有可能把这段JSON数据在所有外发 $。员额()
请求?我试着用头,但Laravel好像没认出来 -
VAR csrf_token = $('元[NAME =CSRF令牌])ATTR(内容)。
警报(csrf_token);
$就prefilter(功能(选项,originalOptions,jqXHR){
如果(选项['型'。与toLowerCase()===后){
jqXHR.setRequestHeader(X-CSRFToken',csrf_token);
}
});
您 $。阿贾克斯prefilter
办法是一个很好的一个。你并不需要添加一个头,虽然;你只需要一个属性添加到数据
字符串。
数据提供的第二个参数 $交
,然后格式化作为查询字符串( ID = FOO和放大器;酒吧=巴兹和放大器; ...
)的prefilter获得访问数据
选项之前。因此,你需要自己的字段添加到查询字符串:
VAR csrf_token = $('元[NAME =CSRF令牌])ATTR(内容)。
$就prefilter(功能(选项,originalOptions,jqXHR){
如果(options.type.toLowerCase()===后){
//添加前导符号,如果`data`非空
options.data + = options.data&放大器;:;
//添加_token进入
options.data + =_token =+ csrf_token;
}
});
这会变成 ID =用户ID
到 ID =用户ID和放大器; _token = csrf_token
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.
While making a simple $.post()
request I received a 'Illuminate\Session\TokenMismatchException'
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
});
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');
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);
}
});
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.
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") {
// add leading ampersand if `data` is non-empty
options.data += options.data?"&":"";
// add _token entry
options.data += "_token=" + csrf_token;
}
});
This will turn id=userID
into id=userID&_token=csrf_token
.
这篇关于jQuery的添加CSRF令牌的所有$。员额()请求“数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!