yii 2 局部关闭 CSRF 拦截

最近用yii2框架做ajax post传值时,报400错误,后来知道是csrf拦截

yii 2.0 内,对 CSRF 攻击做了处理,会对 post 提交的数据做 token 验证,而ajax post 到我们服务器的代码中,没有带上这个 token ,所以会验证失败

现在局部关闭csrf

新建一个Behavior  advancedvendoryiisoftyii2filters

<?php
namespace yiifilters;

use Yii;
use yiiaseActionEvent;
use yiiaseBehavior;
use yiiwebController;

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 yiifiltersNoCsrf;

这样就实现了在action中关闭Csrf而不是在整个Controller中关闭。

原文地址:https://www.cnblogs.com/ssfs/p/6656690.html