Zend Framework CSRF protection

01.Oct.2011

CSRF or Cross-Site Request Forgery is basically a way of requesting an unauthorized commands from a website by using an authorised user.

For example: Let’s assume that you are logged in on your blog and I know that. I could then send you an e-mail with following content: <img src=”http://yoursite.com/?action=delete-article&id=12″ />.

Although you wouldn’t see the image – request for deleting article with id 12 would be sent. This can be prevented by setting up a hidden input in your Zend Framework form with a value that will be posted with your request and validated when request is sent in order to prevent possible CSRF attack.

It is quite easy in Zend Framework to set CSRF protection and here is the snippet:

$form->addElement('hash', 'csrf_token',
            array('salt' => get_class($this) . 'stunt@c0d3rs~!'));

In order to see a full example of Zend Framework CSRF protection I have prepared an example of simple form with no elements on it.

Zend Framework CSRF protection

class Stunt_Form extends Zend_Form
{
    public function init()
    {
        parent::init();
        $this->addElement('hash', 'csrf_token',
                    array('salt' => get_class($this) . 'stunt@c0d3rs~!'));
    }
}