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

problems with csrf

Hi guys, I'm having problems using the csrf of the security component.

This is what happening:

I have an indexAction like this:

public function indexAction()
    {
        $this->view->setVars(array(
            'lastSessionToken' => $this->security->getSessionToken(),
            'token' => $this->security->getToken(),
            'newSessionToken' => $this->security->getSessionToken()
        ));
    }

And this is the view

{{ lastSessionToken }}
<br/>
{{ token}}
<br/>
{{ newSessionToken }}

And an example result is (first time):

cfe1ec0d7755f38f7154fedba5779f56
be60d351a35675294aa7b8d65f6de3a0
be60d351a35675294aa7b8d65f6de3a0

(second time)

6f872476b3f3f30329f1fa011f2878d7
ce9752d9d3170775d29eb00d869129d3
ce9752d9d3170775d29eb00d869129d3

So is not working well, because when I check the last token always I have a new token but I never wanted generate the token again yet.

Testing the application I noticed that the problem is the "javascript_include" that I'm writing before the </body> tag, if I change this writing all the javascript_include in the <head> everthing work perfect.

Can you check how is implemented the javascript_include?

Thanks!! great framework and sorry for my english.

edited Mar '14

I don't see what the CSRF token issue has to do with the javascript_include thing but i could be missing something here ;)

Anyways this is how i implemented it:

Volt:

    {{ form.render('csrf', ['value': security.getToken()]) }}

can also be:

    {{ hidden_field("csrf", "value": security.getToken()) }}

Controller:

    $csrf = new Hidden('csrf');

    $csrf->addValidator(new Identical([
        'value' => $this->security->getSessionToken(),
         'message' => 'Validatie mislukt, probeer het nogmaals.'
     ]));

or just just $this->security->getSessionToken() against the value in $this->request->get('csrf');



16.2k

Hey Im not exactly sure how you are using the security token, but you should see this thread: https://forum.phalcon.io/discussion/922/csrf-protection-not-working

Basically, some of us have encountered a weird issue where having an indexAction as the default route / in the default controller creates some peculiararites with the csrf component.