Yii2 默认开启csrf校验,但是有些时候确实不需要校验,比如对外提供API
一般做法直接在xxController中增加属性:
public $enableCsrfValidation = false;
但是这样整个xxController都失去了校验,开发中又只是希望某一个action禁用
在components下建文件NoCsrf.php,
内容:
1 class NoCsrf extends Behavior 2 { 3 public $actions = []; 4 public $controller; 5 public function events() 6 { 7 return [Controller::EVENT_BEFORE_ACTION => 'beforeAction']; 8 } 9 public function beforeAction($event) 10 { 11 $action = $event->action->id; 12 if(in_array($action, $this->actions)){ 13 $this->controller->enableCsrfValidation = false; 14 } 15 } 16 }
在xxController中增加:
1 public function behaviors() { 2 return [ 3 'csrf' => [ 4 'class' => NoCsrf::className (), 5 'controller' => $this, 6 'actions' => [ 7 'import-data' //actionName 8 ] 9 ] 10 ]; 11 }