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 problems on 2.0.0

I use csrf system identical to vokuro one:

// LoginForm.php

//CSRF
$csrf = new Hidden('csrf');
$csrf->addValidator(
    new Identical(array(
        'value' => $this->security->getSessionToken(),
        'message' => 'CSRF validation failed'
    ))
);
$this->add($csrf);
// login.volt

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

and it's working fine on Phalcon 1.3.4. On 2.0.0 it is working only on first form submit. On every next submit it returns 'CSRF validation failed'.

Any workaround? :I



6.4k
Accepted
answer

getToken returns a new token each time, in your code you are getting the token from session and then generating a new one. I've extended Phalcon\Security with:

public function getOrCreateToken() {
    return $this->_dependencyInjector['session']->get('$PHALCON/CSRF$') ?: $this->getToken();
}


4.7k

thanks, got it working now :)



51.3k

Just FYI,

this could be the reason why your CSRF stopped working:

https://forum.phalcon.io/discussion/8093/csrf-problems-on-206