CSRF verification AJAX call

Hi guys,

I'm trying to verify a CSRF token and it's always failing.. I'm using AngularJS on the client side and making calls to the server via AJAX. I don't think I'm doing anything 'unusual'.... At first I tried to set the token directly in the headers by default, but that didn't work at all, so I figured I'd try to automatically add it to each POST request I'm making, but it's still not working.

In my index.phtml:

    <meta name="csrf_token_name" content="<?php echo $this->security->getTokenKey() ?>">
    <meta name="csrf_token" content="<?php echo $this->security->getToken() ?>">

In my controller:

        $token = $this->request->getPost("CSRFTokenName");
        $tokenKey = $this->request->getPost("CSRFToken");
        $validToken = $this->security->checkToken($tokenKey, $token);
        if (!$this->request->isPost() || !$validToken) {
            $response->setContent(json_encode(array('success'=>false)));
            return $response;
        }

My request does have CSRFTokenName nad CSRFToken in it.

And no, I didn't forget to set the session in DI:

    $di->setShared('session', function () {
        $session = new Phalcon\Session\Adapter\Files();
        $session->start();
        return $session;
    });

$validToken always returns false. I'm wondering what I'm doing wrong?

Thanks!



64.0k

what phalcon version do you use, 2.0.x or 2.1.x ?

I'm using version 2.0.7 I'll try to update, but I'm wondering if it will help at all? Thanks



64.0k

does meta tags being submited via post ?

the way i do it :

<form method="post" action="whatever">
    <input type="hidden" name="<?php echo $this->security->getTokenKey() ?>" value="<?php echo $this->security->getToken() ?>"/>
</form>

and then in controller:

var_dump($this->security->checkToken());

Well, I'm doing it a bit differently, I am adding the tokens directly to the POST data before it's sent off to the server, and in my controller I get the tokens like this:

$token = $this->request->getPost("CSRFTokenName");
$tokenKey = $this->request->getPost("CSRFToken");
$validToken = $this->security->checkToken($tokenKey, $token);

By the way, I'm not building my forms with PHP, I'm using AngularJS and building the forms in HTML and Angular directives



64.0k
edited Nov '15

and if you run in the controller:

echo "<pre>";
print_r($token);
echo "<br>";
print_r($tokenKey);
echo "<br>";
print_r($_SESSION);
echo "<br>";
exit;

also check this https://forum.phalconphp.com/discussion/1878/csrf-problem-with-angular-js and this: http://habrahabr.ru/post/245467/

I found the first link earlier but it didn't help, but the second link looks like it might just help me fix it. I will let you know if I have any problems, thanks!