我从不同的 Controller 和子域发送相同的表单数据。但在一种情况下,我需要禁用 CSRF 验证。
例子:
登录表单:
位置一:example.com主页
位置 2:account.example.com/login
位置 3:
gate.example.com
而且我需要禁用验证以防万一我将数据从位置 1 发送到位置 2。
我使用了 $form = $this->beginWidget('CActiveForm',...
我该怎么做?
我猜 csrf cookie 不是跨域的!
最佳答案
CSRF 验证发生在网页加载过程的早期,甚至在调用 Controller 之前。您想要覆盖 CHttpRequest 类以告诉它忽略某些路由。
在 protected/components
文件夹中创建一个名为 HttpRequest.php
的文件并添加以下内容。
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'));
}
}
}
}
然后,使用以下信息编辑 protected/config
中的配置文件:
// application components
'components'=>array(
....
'request' => array(
'enableCsrfValidation' => true,
'class'=>'HttpRequest',
'noCsrfValidationRoutes'=>array(
'controllername/actionname',
),
),
)
关于php - Yii CSRF 禁用操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16807735/