Another csrf Token problem (probably)

I read most posts about csrf token but I could not find the right answer.
I am testing cakephp 4.3
In 3.x, I often made ajax calls without any particular problem.
Since 4.x, I just can’t make it.

Ajax call :
function togglePublished(el,id) {
var csrfToken = <?= json_encode($this->request->getAttribute('csrfToken')) ?>;
var mydata = ‘?id=’ + id + ‘&csrfToken=’ + csrfToken;
$.ajax({
url: ‘categories/publish’,
type: ‘GET’,
data: mydata,
dataType : ‘html’,
cache: false,
success: function(data) {
// process response
}
});
}
I am always getting an error : “Failed to load resource: the server responded with a status of 500 ()”
Debug.log ans error.log do not give any detail.

1 Like

I reply to myself :slight_smile:
Now I tried a post call :
function togglePublished(el,id) {
var csrfToken = <?= json_encode($this->request->getAttribute('csrfToken')) ?>;
var jsondata = {
“id”:id,
“csrfToken”:csrfToken
};
$.ajax({
type: “POST”,
url: “categories/publish”,
data: jsondata,
contentType: “json”,
success: function(result){
alert(result);
},
error: function() {
alert(“Error”);
}
});
}
It is a little better but still does not work.
I receive a response (error) and still have a server error :
Failed to load resource: the server responded with a status of 403 ()

Error.log says : 2021-05-17 14:14:40 Error: [Cake\Http\Exception\InvalidCsrfTokenException] CSRF token from either the request body or request headers did not match or is missing. in …/vendor/cakephp/cakephp/src/Http/Middleware/CsrfProtectionMiddleware.php on line 408

var csrfToken = <?= json_encode($this->request->getAttribute('csrfToken')) ?>;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById(“geonames”).innerHTML=this.responseText;
}
}
xmlhttp.open(“GET”,“<?php echo $this->Url->build(['controller'=>'Salespoints','action'=>'updategeonames?q=']); ?>”+val,true);
xmlhttp.setRequestHeader(‘X-CSRF-Token’, csrfToken);
xmlhttp.send();

The above is from a pure Javascript example.
Did you set the request Header ?

Thank you for taking care.
It’s late here.
I’ll try this one tomorrow morning.

I am always having this message :
‘_Token’ was not found in request data.
Cake\Controller\Exception\AuthSecurityException

although I have this in my form :
input type=“hidden” name="_csrfToken" autocomplete=“off” value=“9JOgstZoss7Zj1yN1TFGzIIbkeRvieQzcxQ0y9r7k03wes9F6JYIjXNjT0gBVQeNtpFO0AExIit/1AOWn4G4Mpl9FXCiPbEosyyi3Qzq11FCJlaq4pikK5UY+X3Rrz28R1YqLGIxMrSDpnjiMFVHGw==”/>

Im not experienced in jQuery but I think you need to add a request-header somehow like this:

headers: { ‘X-CSRF-Token’: csrfToken }

after:

$.ajax({
url: ‘categories/publish’,…

I tried but it did not work.

I temporarily bypassed CSRF by adding :
if ($this->request->getAttribute(‘identity’)->role_id <=2) {
if ($this->request->getParam(‘prefix’) === ‘Admin’) {
if ($this->request->is(‘ajax’)) {
$this->Security->setConfig(‘validatePost’, false);
}
}
}

in the beforeFilter of the appController

This works perfectly in ajax calls but not sure if I am doing right.

But I’m still having a problem.
Forms are not validated in plugins because of csrf.
Forms work in articles, categories etc.

And all tables and controllers where created using bake.

maybe this could be more helpful:

Thank you.
I’ll study this one.

A friendly tip about formatting: Use code tags (3 back-tics) when pasting in code, as it is far more legible that way.

This:

if ($this->request->getAttribute(‘identity’)->role_id <=2) {
if ($this->request->getParam(‘prefix’) === ‘Admin’) {
if ($this->request->is(‘ajax’)) {
$this->Security->setConfig(‘validatePost’, false);
}
}
}

Can become this:

if ($this->request->getAttribute('identity')->role_id <=2) {
    if ($this->request->getParam('prefix') === 'Admin') {
        if ($this->request->is('ajax')) {
            $this->Security->setConfig('validatePost', false);
        }
    }
}

By placing your code inbetween three back-tics, like so:

```php
// Paste PHP code here
```

php behind the first 3 back-ticks denotes the language (code is in PHP), but you can change or remove this.

1 Like

Thank you and sorry :slight_smile:

1 Like