最近用yii2框架做ajax post传值时,报400错误,后来知道是csrf拦截
yii 2.0 内,对 CSRF 攻击做了处理,会对 post 提交的数据做 token 验证,而ajax post 到我们服务器的代码中,没有带上这个 token ,所以会验证失败
现在局部关闭csrf
新建一个Behavior advanced\vendor\yiisoft\yii2\filters
php
namespace yii\filters;use Yii;
use yii\base\ActionEvent;
use yii\base\Behavior;
use yii\web\Controller;class NoCsrf extends Behavior
{public $actions = [];public $controller;public function events(){return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];}public function beforeAction($event){$action = $event->action->id;if(in_array($action, $this->actions)){$this->controller->enableCsrfValidation = false;}}
}
然后在Controller中添加Behavior
public function behaviors(){return ['verbs' => ['class' => VerbFilter::className(),'actions' => ['delete' => ['POST'],],],
'csfr' => ['class' => NoCsrf::className(),'controller' => $this,'actions' => ['prize' //需要禁用csrf的方法]],];}
其中,在控制器中要引用该类 use yii\filters\NoCsrf;
这样就实现了在action
中关闭Csrf
而不是在整个Controller
中关闭。