How to define CSRF token in ajax call in Cakephp 3. Also How CSRF can be off for some ajax requests
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>
You can then easily use it in all your AJAX requests:
setRequestHeader('X-CSRF-Token', csrfToken);
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);
}
}
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
See also
- Cookbook > Request & Response Objects > Request Parameters
- Cookbook > Controllers > Components > CSRF > Using the CsrfComponent
- Cookbook > Controllers > Components > CSRF > Disabling the CSRF Component for Specific Actions
Every form has a hidden _csrfToken
field that's automatically added when you have enabled the Csrf component. Now you can easily get the token of this field by jquery like $('[name="_csrfToken"]').val()
.
A ajax call will look like this:
$.ajax({
url: 'someUrl',
headers : {
'X-CSRF-Token': $('[name="_csrfToken"]').val()
},
type: 'post',
...
});