I have CSRF validation on a global basis. However this is breaking when making AJAX calls from another domain (I’m creating a REST service). Is there a way I can disable it for individual controller methods?
I have CSRF validation on a global basis. However this is breaking when making AJAX calls from another domain (I’m creating a REST service). Is there a way I can disable it for individual controller methods?
class HttpRequest extends CHttpRequest {
public $noCsrfValidationRoutes = array();
protected function normalizeRequest()
{
parent::normalizeRequest();
$route = Yii::app()->getUrlManager()->parseUrl($this);
if($this->enableCsrfValidation && false!==array_search($url, $this->noCsrfValidationRoutes))
Yii::app()->detachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
}
}
(original event - onBeginRequest - with capital "B", code block changed case)
in main.php:
'components'=>array(
..
..
'request'=>array(
'class'=>'HttpRequest',
'noCsrfValidationRoutes'=>array('site/something'),
),
Thanks for this, I have a problem however…
if($this->enableCsrfValidation && false!==array_search($url, $this->noCsrfVa...
What is the value of $url as it is undefined and causing it to fail…
that should be $route not $url.
Just tried that, but csrf is still enabled on the controller/methods i specify.
then use var_dump($route); to see what’s returned and see if what matches the format of the urls you entered in the array.
There is a small catch in the code above, if you want to match a controller action you have to ignore the parameters, I think I achieve that with the code below.
class HttpRequest extends CHttpRequest
{
public $noCsrfValidationRoutes=array();
protected function normalizeRequest()
{
parent::normalizeRequest();
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'));
}
}
}
}