Home > Symfony Framework > How to change CSRF attack message in Symfony 1.2

How to change CSRF attack message in Symfony 1.2

July 15th, 2010

I wanted to change the symfony 1.2 CSRF attack message from “CSRF attack detected.” to “This session has expired. Please return to the home page and try again.”.

The default scary error message is hard coded in sfValidatorCSRFToken.class.php like this:

$this->addMessage('csrf_attack', 'CSRF attack detected.');

There aren’t that many clues out there about how to change it without modifying the core class either. Kris Wallsmith (Symfony Release Manager) suggested I look at using event dispatcher. Then I found his article on the net which gave me more clues.

So here’s the solution that I ended up with. First let’s create a listener class and save it in the project lib folder as myTemplateFilterParametersListener.php

class myTemplateFilterParametersListener
{
  public function connect(sfEventDispatcher $dispatcher)
  {
    $dispatcher->connect('template.filter_parameters',
      array($this, 'filterParameters'));
  }
 
  public function filterParameters(sfEvent $event, $parameters)
  {
    foreach ($parameters as $name => $param)
    {
      if ($param instanceof sfForm)
      {
        $form = $param; /* @var $form sfForm */
 
        self::changeCSRFErrorMessage($form);
      }
    }
 
    return $parameters;
  }
 
  public static function changeCSRFErrorMessage(sfForm $form)
  {
    $errors = $form->getErrorSchema()->getNamedErrors();
    if ($errors)
    {
      foreach ($errors as $i => $error)
      { /* @var $error sfValidatorError */
 
        if ($i == '_csrf_token')
        {
          $validator = $error->getValidator();
          /* @var $validator sfValidatorCSRFToken */
          $validator->setMessage('csrf_attack', 'This session has expired. Please return to the home page and try again.');
        }
      }
    }
  }
}

Then hook it to the event dispatcher in apps/frontend/config/frontendConfiguration.class.php

 
class frontendConfiguration extends sfApplicationConfiguration
{
  public function  initialize() {
    $listener = new myTemplateFilterParametersListener($this->getConfigCache());
    $listener->connect($this->dispatcher);
  }
 
  public function configure()
  {
  }
}

./symfony cc

That’s it :)

Use Firebug to test it. Open your webpage containing the form, use Firebug to change the _csrf_token value to trigger CSRF attack error, and you should see “This session has expired. Please return to the home page and try again.” error message.

Related posts:

  1. How to make Symfony session to never timeout This is fo

Related posts brought to you by Yet Another Related Posts Plugin.

Symfony Framework

  1. No comments yet.
  1. No trackbacks yet.
Subscribe to comments feed