在特定动作上禁用CSRF CakePHP 3 [英] Disabling CSRF on a specific action CakePHP 3
问题描述
因此,我有一个使用 DataTables 自动生成的表。 CakePHP中的一个动作将获取该表的数据,并将其格式化为JSON以供数据表使用,这是格式化的JSON:
So, I have a table that is auto-generated using DataTables. An action in my CakePHP grabs the data for that table, and formats it into JSON for datatables to use, this is the formatted JSON:
<?php
$data = array();
if (!empty($results)) {
foreach ($results as $result) {
$data[] = [
'name' => $result->name,
'cad' => $this->Number->currency($result->CAD, 'USD'),
'usd' => $this->Number->currency($result->USD, 'USD'),
'edit' => '<a href="' .
$this->Url->build(['controller' => 'Portfolios', 'action' => 'edit', $result->id]) .
'"><i class="fa fa-pencil"></i></a>',
'delete' => '<input type="checkbox" class="delete" value="' . $result->id . '">'
];
}
}
echo json_encode(compact('data'));
如您所见,我在其中有一个删除选项,输出带有值的复选框相应元素的ID的值。选中该复选框后,将显示一个删除按钮,该按钮发送此ajax请求:
As you can see, I have a 'delete' option in there that outputs a checkbox with the value of the id of the corresponding element. When that checkbox is checked, a delete button is showing which sends this ajax request:
$('a#delete').on('click', function(e) {
e.preventDefault();
var checkedValues = [];
$('input.delete:checked').each(function() {
checkedValues.push($(this).val());
});
$.ajax({
url: $(this).attr('href'),
type: 'POST',
data: checkedValues
});
})
此ajax帖子转到我的控制器操作delete()。我遇到的问题是,我收到一条错误消息,指出无效的Csrf令牌。我知道为什么会这样,我正在提交一个启用Csrf保护的表单,其中没有添加Csrf令牌。
This ajax post goes to my controller action delete(). The problem I'm having is that I'm getting an error that states "Invalid Csrf Token". I know why this is happening, I'm submitting a form with Csrf protection on, that has no Csrf token added to it.
我不知道如何为此,请手动创建一个Csrf令牌(在页面加载后生成输入值)。我也无法弄清楚如何禁用Csrf保护。我阅读了此,但代码位于beforeFilter函数中,据我所知,这意味着它可以在所有操作上运行,而不仅是这个操作,也不是我想要的。另外,说实话,我更喜欢不停用安全功能的解决方案。
I can't figure out how to manually create a Csrf token for this situation (where the input values are generated after the page has loaded). Nor can I figure out how to disable Csrf protection. I read this, but the code is placed in the beforeFilter function, and as far as I understand it, that means it's run on every action, not just this one, and that's not what I want. Plus, to be completely honest, I would prefer a solution where I don't deactivate security functions.
是否有针对此特定操作禁用Csrf的方法,或者存在
Is there anyway to disable Csrf for this specific action, or is there a better way to do this?
推荐答案
在此处详细了解CSRF组件
read all about the CSRF component here
http://book.cakephp.org/3.0/en /controllers/components/csrf.html
您可以在此处禁用特定操作:
you can disable for a specific action here:
public function beforeFilter(Event $event) {
if (in_array($this->request->action, ['actions_you want to disable'])) {
$this->eventManager()->off($this->Csrf);
}
}
这篇关于在特定动作上禁用CSRF CakePHP 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!