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

Phalcon CSRF after update from 1.3.4

Hello to everyone, Sorry if i set wrong form, could not find Form section and volt is also something different.

we are trying to update to latest version of phalcon, and got problem with csrf. Actually not with csrf, with form that shows it.

Scenario:

  1. On first load everything works fine.
  2. Validation failed.
  3. Form generates old value in form.
  4. And every request is using first value

Code:

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

   //controller 
   if ($form->isValid($this->request->getPost())) { .... }

   //view
   {% set security_token = security.getToken() %}
   {{ form.render(name, ['value': security_token]) }}

I see in code that actually security_token is changing on each request. But value is ignored. As i understand from framework code https://github.com/phalcon/cphalcon/blob/master/phalcon/forms/element.zep It uses POST values on top of attributes from form, so POST overrides this value. (Actually if reset POST value for csrf, everything works )

I understand i can use Tag and generate manually this field, but i see everywhere such examples, may be i missed something? Also we have quite a lot of forms, so it will require time to update everything, so i hope someone here can help me.

Thank you.



681

Looks like i solved it.

From documentation https://docs.phalcon.io/ru/latest/reference/forms.html#id1 , and code for element i got that phalcon asks value from form at first place so:

public function getCsrf()
{
    //return $this->security->getToken();//takes  value from session, not something i need
    return $this->security->getSessionToken();//new generated value to use in form
}

And for validation it use values from POST and SESSION so should not affect validation.



681

I have adapted Phalcon collection to MongoDB driver, can share it if needed.