jQuery 将 CSRF 令牌添加到所有 $.post() 请求的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28417781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery add CSRF token to all $.post() requests' data
提问by NightMICU
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.
我正在开发一个 Laravel 5 应用程序,该应用程序默认为所有 POST 请求启用 CSRF 保护。我喜欢这种增加的安全性,所以我正在尝试使用它。
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:
在发出一个简单的$.post()
请求时,我收到一个'Illuminate\Session\TokenMismatchException'
错误,因为_token
POST 数据中缺少所需的表单输入。这是有问题的 $.post 请求的示例:
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:
我将我的 CSRF 令牌作为元字段存储在我的标头中,并且可以使用以下方法轻松访问它:
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 -
是否可以将其附加到所有传出$.post()
请求的 json 数据中?我尝试使用标题,但 Laravel 似乎无法识别它们 -
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);
}
});
回答by apsillers
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.
你的$.ajaxPrefilter
方法很好。不过,您不需要添加标题;您只需要向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:
数据作为 的第二个参数提供$.post
,然后id=foo&bar=baz&...
在预过滤器访问data
选项之前格式化为查询字符串 ( ) 。因此,您需要将自己的字段添加到查询字符串中:
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);
}
});
This will turn id=userID
into id=userID&_token=csrf_token
.
这将id=userID
变成id=userID&_token=csrf_token
.
回答by Kornel
From Laravel documentation:
从 Laravel 文档:
You could, for example, store the token in a "meta" tag:
Once you have created the meta tag, you can instruct a library like jQuery to add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
例如,您可以将令牌存储在“元”标签中:
创建元标记后,您可以指示像 jQuery 这样的库将令牌添加到所有请求标头。这为基于 AJAX 的应用程序提供了简单、方便的 CSRF 保护:
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
So for example you can do request like below.
因此,例如,您可以执行如下请求。
Add this meta tag to your view:
将此元标记添加到您的视图中:
<meta name="csrf-token" content="{{ csrf_token() }}">
And this is an example script which you can communicate with Laravel (sends request when you click an element with id="some-id" and you can see the response in an element with id="result"):
这是一个示例脚本,您可以与 Laravel 通信(当您单击 id="some-id" 的元素时发送请求,您可以在 id="result" 的元素中看到响应):
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$("#some-id").on("click", function () {
var request;
request = $.ajax({
url: "/your/url",
method: "POST",
data:
{
a: 'something',
b: 'something else',
},
datatype: "json"
});
request.done(function(msg) {
$("#result").html(msg);
});
request.fail(function(jqXHR, textStatus) {
$("#result").html("Request failed: " + textStatus);
});
});
});
</script>
回答by Alex Baklanov
Generally I agree with the concept Kornel suggested except one thing.
一般来说,我同意 Kornel 建议的概念,除了一件事。
Yes, Laravel's docs advice to use $.ajaxSetup
, but it's not recommended since this method affects all the subsequent ajax requests. It is more correctly to set the ajax settings for each request. Though you can re-set stuff:
是的,Laravel 的文档建议使用$.ajaxSetup
,但不推荐使用,因为此方法会影响所有后续的 ajax 请求。为每个请求设置ajax设置更正确。虽然你可以重新设置东西:
All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup()
使用任何函数的所有后续 Ajax 调用都将使用新设置,除非被单个调用覆盖,直到下一次调用 $.ajaxSetup()
If you use $.ajax()
, it's more convenient to utilize either data
property or headers
. Laravel allows CSRF-token both as a request parameter or a header.
如果使用$.ajax()
,则使用data
property 或headers
. Laravel 允许 CSRF 令牌作为请求参数或标头。
First, you add the following meta tag into the view
首先,将以下元标记添加到视图中
<meta name="csrf-token" content="{{ csrf_token() }}">
And then make an ajax request either way:
然后以任何一种方式发出 ajax 请求:
$.ajax({
url: "/your/url",
method: "POST",
data:
{
a: 'something',
b: 'something else',
_token: $('meta[name="csrf-token"]').attr('content')
},
datatype: "json"
});
OR
或者
$.ajax({
url: "/your/url",
method: "POST",
data:
{
a: 'something',
b: 'something else',
},
headers:
{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
datatype: "json"
});
回答by phk
The Django documentation on CSRFgives a nice code snippet with ajaxSetup
for automatically adding the appropriate header to all request types where it matters:
CSRF 上的Django 文档提供了一个很好的代码片段,ajaxSetup
用于自动将适当的标头添加到所有重要的请求类型:
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); } } });
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); } } });
回答by c319113
there is a much easier method to do this you can serialize the data like so before sending
有一种更简单的方法可以做到这一点,您可以在发送之前像这样序列化数据
<form method="post" id="formData">
<input type="text" name="name" >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" id="sub" class="btn btn-default" value="Submit" />
</form>
<script>
$(document).on('submit', '#formData', function (event) {
event.preventDefault();
var formData = $('#formData').serialize();
$.ajax({
url: url,
type: "POST",
data : formData,
success: function (result) {
console.log(result);
}
});
});
});
</script>
everything with a name attr will be put in to a query and submited
具有名称 attr 的所有内容都将放入查询并提交
回答by Amir Karamat
no need to set any meta tagneither the csrf_token()nor the csrf_field()!
无需设置任何元标记,无论是csrf_token()还是 csrf_field()!
You could use this jQuery snippet :
你可以使用这个 jQuery 片段:
$.ajaxPrefilter(function( settings, original, xhr ) {
if (['post','put','delete'].includes(settings.type.toLowerCase())
&& !settings.crossDomain) {
xhr.setRequestHeader("X-XSRF-TOKEN", getCookie('XSRF-TOKEN'));
}
});
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;
}
just few other answers tried to set the csrf header but according the Laravel documents (here) , the header key should be "X-XSRF-TOKEN"and Laravel itself provides the needed value on every request for us in a cookie named "XSRF-TOKEN"
只有少数其他答案尝试设置 csrf 标头,但根据 Laravel 文档(此处),标头键应为“X-XSRF-TOKEN”,Laravel 本身在名为“XSRF-”的 cookie 中为我们提供每个请求所需的值代币”
so just corrected the keys and edited few lines,thanks
所以只是更正了键并编辑了几行,谢谢
回答by Kamil Latosinski
I think that above solution might not work as well. When you do:
我认为上述解决方案可能也行不通。当你这样做时:
var x;
x + ""
// "undefined" + empty string coerces value to string
You will get data like "undefined_token=xxx"
你会得到像“undefined_token=xxx”这样的数据
When you use the above solution for laravel's delete for instance you have to check like this:
例如,当您将上述解决方案用于 laravel 的删除时,您必须像这样检查:
if (typeof options.data === "undefined")
options.data = "";
else
options.data += "&";
options.data = "_token=" + csrf_token;