Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii CSRF disable for action

Tags:

php

csrf

yii

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!

like image 402
spy-enot Avatar asked May 29 '13 07:05

spy-enot


2 Answers

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',
        ),
    ),
 )
like image 97
Willem Renzema Avatar answered Oct 11 '22 15:10

Willem Renzema


To disable CSRF add this code to your controller:

public function beforeAction($action) {
    $this->enableCsrfValidation = false;
    return parent::beforeAction($action);
}
like image 33
thelittlebug Avatar answered Oct 11 '22 14:10

thelittlebug