ZF-5182: Zend_Form_Element_Hash not yet set in session

Description

I have the following problem. On the very first page of a project i'm working on there is a form. For CSRF protection I've added:

    $no_csrf_hash = new Zend_Form_Element_Hash('no_csrf_hash');
    $no_csrf_hash->setSalt(md5(rand(0,1000)));
    $this->addElement($no_csrf_hash);  

This works like a charm, except when i go to the website for the first time (starting a new session). The session cookie is set, however it seems that the 'Zend_Form_Element_Hash_salt_no_csrf_hash' key is not yet registered.

Zend_Debug::dump($_SESSION);

Results the first time in: array(0) {}

After a reload (F5) it is properly filled with: array(1) { ["__ZF"] => &array(1) { ["Zend_Form_Element_Hash_salt_no_csrf_hash"] => array(1) { ["ENT"] => int(1228748259) } } }

I've tried with and without the strict-option when starting the session in the bootstrap, both to no avail. Could it be a bug?

Thanks in advance, Fili

Comments

I have the same problem in my login form that is the very first page of site.

I examined this issue and noticed that in the first page load, when there isn't existing sessions, the value of hash is null. After reloading the page the hash is set correctly. I overcame the problem by editing the render method of the hash element class and call initCsrfToken() twice. This seemed to fix the problem, although in nasty way. But I hope this might help to localize what's the real problem.


    public function render(Zend_View_Interface $view = null)
    {
        $this->initCsrfToken();
-->     $this->initCsrfToken();
        return parent::render($view);
    }

The solution above doesn't work any more in 1.9.6. It did work in 1.9.5.

I think other issues with the hash element were fixed around the 1.9.6 time, can you check that the expected usage works (as opposed to the hack)?

Ralph, I do not have a clue what is happening with the hash. It is working and then suddenly not working. Even one of my clients run into this problem, and at the same time the form was working for me. You can check my recent experience from ZF-10714.

I think you can close this issue and we can keep the most recent one.

Does this problem still persist? If so, is it with the framework or the browser? A lot of these wishy-washy Zend_Session-related bugs appear to be falling into the "concurrent requests returning 404 errors cause competing sessions to be initiated" issue (primarily with Google Chrome)

Adam–I have seen this happening in firefox too and also in chrome with correctly placed favicon, but that was a year ago. Since then I decided not to use csrf or at least avoid using it. Atm. I do not have zf1 projects going on so it's hard to say if this still persist or not.