We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

CSRF dont work with JSON requests

Hi,

I had a problem with CSRF, my token was always false and I finally find out why :

I'm sending my form values with an Ajax request to my ajaxController using JSON format !

Here's my code where my token is always false :

public function registerAction() {

$post   =   $this->request->getJsonRawBody();

// checkToken() returns false everytime
if($post && $this->security->checkToken())  {

// DO STUFF with $post values
}

}

To make it works i have to force $_POST values using my json values like that :

public function registerAction() {

$post   =   $this->request->getJsonRawBody();

foreach($post as $postName => $postValue) {

            $_POST[$postName]   =   $postValue;
        }

// checkToken is now working
if($post && $this->security->checkToken())  {

// DO STUFF
}

}

So i'm sharing this problem to everyone who might be in this case, and i'm asking : is there any better/proper way to make it works ? And maybe checkToken() should handle this case ?

Thanks.

Btw : How does syntax highlighter works ? :D

Re: Syntax highlighter: The backticks need to be consecutive - no spaces separating them.

Wow i didn't noticed them, Thanks!

Anyway, I'm still open to any suggestion about my "problem".



2.2k

checkToken() checks $_POST by default.

So you need to pass 2 args:

checkToken ([string $tokenKey], [string $tokenValue])

https://docs.phalcon.io/en/latest/api/Phalcon_Security.html