2011-04-09 10:23:08

CSRF validation with Web Service

Created by lexand at 2010-05-17 07:53:44 (last change 2011-04-09 10:23:08)  
Category: Yii

Some times ago I need to use SOAP in one of my application.

As the first step I had implemented example written on the Yii site. But after executing I got CHttpException.

I got this exception because CSRF validation was enabled. And I can't switch it off, it must be always enabled.

I found this solution http://www.yiiframework.com/forum/index.php?/topic/8689-disable-csrf-verification-per-controller-action/

I had added 'services/wsdl' to the $noCsrfValidationRoutes, but I still got CHttpException, beacuse the real route is 'services/wsdl/ws/1'.

That's why I'd decided to make little changes to HttpRequest class.

/**
 * Description of HttpRequest
 *
 *
 * Used in config/main.php
 * <pre>
 *    'request'=>array(
 *        'class'=>'HttpRequest',
 *        'noCsrfValidationRoutes'=>array(
 *            '^services/wsdl.*$'
 *        ),
 *        'enableCsrfValidation'=>true,
 *        'enableCookieValidation'=>true,
 *    ),
 * </pre>
 *
 * Every route will be interpreted as a regex pattern.
 *
 * @author alex
 */
class HttpRequest extends CHttpRequest {
    public $noCsrfValidationRoutes = array();

    protected function normalizeRequest(){
        parent::normalizeRequest();
        
        if($_SERVER['REQUEST_METHOD'] != 'POST') return;

        $route = Yii::app()->getUrlManager()->parseUrl($this);
        if($this->enableCsrfValidation){
            foreach($this->noCsrfValidationRoutes as $cr){
                if(preg_match('#'.$cr.'#', $route)){
                    Yii::app()->detachEventHandler('onBeginRequest',
                        array($this,'validateCsrfToken'));
                    Yii::trace('Route "'.$route.' passed without CSRF validation');
                    break; // found first route and break
                }
            }
        }
    }

}
При использовании материалов сайта ссылка на источник обязательна.
When using the site materials please make reference to the source.

[ Add comment ]