防护形式的篡改是由安全组件提供的基本功能之一。只要启用,它将把所有POST视为表单提交。
定期手动编码的HTML表单在启用安全组件时不起作用,因此JQuery生成的POST也不会生效。当然,您可以使用$this->Security->validatePost = false;
或$this->Security->csrfCheck = false;
,但是这时您将失去安全组件提供的保护。
为了保持安全组件正常运行,您需要使用CakePHP Form Helper来创建您要通过ajax发布的表单。通过这种方式,data[_Token][fields]
和data[_Token][unlocked]
隐藏字段得到与他们的密钥生成:
<?php
echo $this->Form->create('Test',array('id'=>'testform'));
echo $this->Form->input('Something');
echo $this->Form->submit();
echo $this->Form->end();
?>
这会产生这样的事情:
<form action="/your/url" id="testform" method="post" accept-charset="utf-8">
<div style="display:none;">
<input type="hidden" name="_method" value="POST"/>
<input type="hidden" name="data[_Token][key]" value="9704aa0281d8b5a2fcf628e9fe6f6c8410d8f07a" id="Token937294161"/>
</div>
<div class="input text">
<input name="data[Test][Something]" class="required" type="text" id="TestSomething"/>
</div>
<div class="submit">
<input type="submit" />
</div>
<div style="display:none;">
<input type="hidden" name="data[_Token][fields]" value="0c81fda1883cf8f8b8ab39eb15d355eabcfee7a9%3A" id="TokenFields817327064"/>
<input type="hidden" name="data[_Token][unlocked]" value="" id="TokenUnlocked281911782"/>
</div>
</form>
现在它只是一个在JQuery的序列化这种形式的物质使之能与ajax POST一起发送:
$('#testform').submit(function(event) {
$.ajax({
type: 'POST',
url: "/your/url",
data: $('#testform').serialize(),
success: function(data){
alert('Wow this actually worked');
},
error:function() {
alert('This will never work');
}
});
event.preventDefault(); // Stops form being submitted in traditional way
});
现在,如果按下提交按钮,POST将成功。
重要:由于该表单辅助的令牌只能与安全组件中使用一次的事实,这个解决方案,如果你只打算POST每页代一次才有效。如果您需要能够多次发布相同的形式重新加载页面之间,那么你就需要做到以下几点,当你在你的控制器的开头添加安全组件:
public $components = array(
'Security' => array(
'csrfUseOnce' => false
)
);
...这将允许令牌用于多个请求。这不是作为安全,但您可以将其与csrfExpires
结合使用,以便令牌最终过期。这全部记录在CSRF configuration section of the Cake book中。
我正在调查这个,我很确定它的安全组件阻止我在这里: http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html – kSeudo
好吧如果我禁用这个跨站点安全:$ this-> Security-> csrfCheck = false; 它的工作.....但显然这是不是要走的路:) 任何想法? – kSeudo
你可以在/ usermgmt/users/editUser中发布代码 – Leo