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

Issues with CSRF check

Hi,

I'm having issues with my CSRF checks, they were working and suddenly stopped. It may have been something I've changed, but I'm fairly sure it isn't.

I have sessions set up in my bootstrap:

$this->di->setShared('session', function() {
    $session = new Session();
    $session->start();
    return $session;
});

I'm using CSRF by creating it in my form using a trait, the trait consists of the following: (I've excluded namespaces etc for the exmaple)

trait CsrfTrait
{

    /**
     * Get CSRF
     *
     * @return string
     */
    public function getCsrf()
    {
        return $this->security->getToken();
    }

    /**
     * Add CSRF
     *
     * @return void
     */
    protected function addCsrf()
    {
        $csrf = new Hidden('csrf');
        $csrf->addValidators([
            new Validator\PresenceOf([
                'message' => 'CSRF token is required',
            ]),
            new Validator\Identical([
                'value' => $this->security->getSessionToken(),
                'message' => 'CSRF token validation failed',
            ]),
        ]);
        $csrf->clear();
        $this->add($csrf);
    }
}

The addCsrf() method is called from a initialize() call in the form classes. In my volt views I then call {{ form.render('csrf') }} which adds the hidden input.

The issue I'm now having is that it is failing validation as the session token is somehow different to what has been populated in the form.

Is there any reason why this would have stopped working? Or something I may have done that would broken this?

Thanks, Gary

To clarify, Session is in fact Phalcon\Session\Adapter\Files.

Hi @Gary check this issue CSRF check token

Good luck



6.5k
Accepted
answer

Ok, I'm not sure what happened but it seemed to be after I added a security plugin for ACL. I commented it out and it all started working again, uncommented it again and everything was still working as expected.

Gary