如何在Cakephp 3中的ajax调用中定义CSRF令牌。以及如何为某些ajax请求关闭CSRF [英] How to define CSRF token in ajax call in Cakephp 3. Also How CSRF can be off for some ajax requests
问题描述
在Cakephp3中,启用Csrf组件。我如何在ajax调用中使用它。
在头文件中设置ajax csrf令牌的 beforeSend
参数。 csrfToken
的值是多少。
In Cakephp3 when the Csrf component is enabled. How I can use it in ajax call.
In this beforeSend
parameter of ajax csrf token is set in header. What is the value of csrfToken
. As it gives error
csrfToken未定义
csrfToken is not defined
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
另外,如何为某些ajax调用禁用Csrf组件。
Also how can I disable Csrf component for some ajax calls.
推荐答案
CSRF组件将当前令牌作为 _csrfToken
写入请求参数中,可以通过请求对象的 param()
方法(或从CakePHP 3.4开始的 getParam()
)获取它:
The CSRF component writes the current token to the request parameters as _csrfToken
, you can get it via the request object's param()
method (or getParam()
as of CakePHP 3.4):
beforeSend: function(xhr){
xhr.setRequestHeader(
'X-CSRF-Token',
<?= json_encode($this->request->param('_csrfToken')); ?>
);
},
要使令牌可用于所有脚本,例如,可以使令牌在全球范围内可用布局模板中的变量:
To make the token available to all your scripts, you can for example make it globally available as variable in your layout template:
<script>
var csrfToken = <?= json_encode($this->request->param('_csrfToken')) ?>;
// ...
<script>
然后,您可以轻松地在所有AJAX请求中使用它:
You can then easily use it in all your AJAX requests:
setRequestHeader('X-CSRF-Token', csrfToken);
可以通过从控制器事件管理器中删除CSRF组件来禁用它。您必须确定需要执行的条件,例如针对特定的操作,例如:
The CSRF component can be disabled by removing it from the controllers event manager. You'll have to figure on what condition you'd need to do that, for example for a specific action, like this:
public function beforeFilter(\Cake\Event\Event $event)
{
parent::beforeFilter($event);
if ($this->request->param('action') === 'actionXyz') {
$this->eventManager()->off($this->Csrf);
}
}
如果您使用的是CSRF中间件,那么令牌仍然可用作为名为 _csrfToken
的请求参数,禁用中间件的工作原理有所不同,例如,请参见 Cakephp 3.5.6禁用控制器的CSRF中间件
If you're using the CSRF middleware, then the token is still available as a request parameter named _csrfToken
, disabling the middleware however works differently, see for example Cakephp 3.5.6 disable CSRF Middleware for controller
另请参见
- Cookbook > Request & Response Objects > Request Parameters
- Cookbook > Controllers > Components > CSRF > Using the CsrfComponent
- Cookbook > Controllers > Components > CSRF > Disabling the CSRF Component for Specific Actions
这篇关于如何在Cakephp 3中的ajax调用中定义CSRF令牌。以及如何为某些ajax请求关闭CSRF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!