Yii CSRF disable for action

spy-enot picture spy-enot · May 29, 2013 · Viewed 19.4k times · Source

I send same form data from different contollers and subdomain. But in one case I need disable CSRF validation.

Example:

Login form:

  • Location 1: main page example.com

  • Location 2: account.example.com/login

  • Location 3: gate.example.com

And I need disable validation just in case when I send data from location 1 to location 2.

I Used $form = $this->beginWidget('CActiveForm',...

How can I do that?

I supose that csrf cookie is not crossdomain!

Answer

Willem Renzema picture Willem Renzema · May 29, 2013

CSRF validation occurs early in the process of loading the webpage, even before a controller is called. You want to override the CHttpRequest class to tell it to ignore certain routes.

Create a file in your protected/components folder named HttpRequest.php and add the following contents.

class HttpRequest extends CHttpRequest
{
    public $noCsrfValidationRoutes=array();

    protected function normalizeRequest()
    {
            //attach event handlers for CSRFin the parent
        parent::normalizeRequest();
            //remove the event handler CSRF if this is a route we want skipped
        if($this->enableCsrfValidation)
        {
            $url=Yii::app()->getUrlManager()->parseUrl($this);
            foreach($this->noCsrfValidationRoutes as $route)
            {
                if(strpos($url,$route)===0)
                    Yii::app()->detachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
            }
        }
    }
}

Then, edit your config file in protected/config with the following information:

    // application components
'components'=>array(
    ....

    'request' => array(
        'enableCsrfValidation' => true,
        'class'=>'HttpRequest',
        'noCsrfValidationRoutes'=>array(
            'controllername/actionname',
        ),
    ),
 )