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.
I reply to myself
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
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==”/>
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.