user1217974
user1217974

Reputation: 154

phalcon php csrf token validation fails when working via ajax

Im am working with the phalcon Framework and i decided to work with the csrf function available. I followed all the steps needed as shown in documentation.

I receive the data, the token and its value and i run

$data = $this->request->getJsonRawBody();
print_r($data); //// proper data
if ($this->request->isPost()) {
        if ($this->security->checkToken()) {
            die('proper token');
        }
        else{die('NOT A proper token');}
    }

And my post request is like this :

$scope.submit = function() {    
                $scope.formData.token = [$("#token").attr("name"), $("#token").val()];        

                $http.post(
                    'http://localhost/project/index/function', 
                    JSON.stringify($scope.formData)
                ).success(function(data) { alert(data);
                    if (data.isValidToken) {
                        alert("Ok, you win!!!");
                    } else {
                        alert("Sorry, not valid CSRF !!!")
                    }
                });
                return false;
            };

i check the session data, the tokens stored there while generating the form are different than the one's i print out when the ajax request is done . Could someone point me what im doing wrong ?

Upvotes: 1

Views: 2663

Answers (1)

alu
alu

Reputation: 456

Phalcon\Security::checkToken is use $_POST by default. If you need use ajax, pass tokenKey and tokenValue to Phalcon\Security::checkToken.

Check here

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

if ($this->request->isPost()) {
    $tokenKey = $this->session->get('$PHALCON/CSRF/KEY$');
    $tokenValue = $data->{$tokenKey};
    if ($this->security->checkToken($tokenKey, $tokenValue)) {
        die('proper token');
    }
    else{die('NOT A proper token');}
}

Upvotes: 1

Related Questions