CSRF protection revisited

Tags:

Yesterday, I was talking on IRC with Tom Graham. He was looking for a way to protect GET requests against CSRF. I showed him my CSRF protection plugin, as it would be suitable for protecting GETs too with minor modifications.

This got me thinking what would be the best way to allow you to easily protect certain URLs with it, and here’s the solution…

The dynamic duo

One pattern in Zend Framework apps seems to be that often there is a controller plugin, and an action helper, which exposes the controller plugin’s functionality for easy usage in action controllers.

This is the case here as well:

I’ve modified the CsrfProtect plugin to accomodate the usage in the helper. The helper is completely new, and has methods that you can use in actions to get the CSRF token and check the validity of values in tokens.

Usage

The plugin’s usage is exactly the same as before, so refer to the csrf plugin post for help on that.

Using the action helper is quite simple.

First, we have the initial action and its view:

public function firstAction()
{
    //Assign a token to the view
    $this->view->token = $this->_helper->csrf->getToken();
}
 
//The view:
<a href="secondAction?token=<?= $this->token; ?>">Go to secondAction</a>

And in the second action…

public function secondAction()
{
    //This action is linked from the view in firstAction, and we want to confirm the token:
    $token = $this->getRequest()->getQuery('token');
    if(!$this->_helper->csrf->isValidToken($token))
        throw new Exception('CSRF Token validation failed');
}

Using the helper, you can easily utilize the automatic token generation and all that of the CSRF protection plugin. And it isn’t only limited to GETs either – you could pass the token from the helper to cookies or anything you’d like.