Yii CSRF disable for action

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',
        ),
    ),
 )

As a name suggest it is Cross-Site-Request-Forgery, so no it is not crossdomain and must not be:)

CSRF is enabled in request component, so just get request component and reconfigure it:

Yii::app()->request->enableCsrfValidation = false;

Im not quite sure where to put it, probably in the beginning of action.


To disable CSRF add this code to your controller:

public function beforeAction($action) {
    $this->enableCsrfValidation = false;
    return parent::beforeAction($action);
}

Tags:

Php

Csrf

Yii