Disable CSRF validation for individual actions in Yii2

前端 未结 4 1598
北恋
北恋 2020-11-27 16:52

Is there a way to disable CSRF validation for some actions of the controller keeping it enabled for the other ones?

In my case I have several configurable Action cla

相关标签:
4条回答
  • 2020-11-27 16:59

    For the specific controller / actions you can disable CSRF validation like so:

    use Yii;
    
    ...
    
    Yii::$app->controller->enableCsrfValidation = false;
    

    Or inside a controller:

    $this->enableCsrfValidation = false;
    

    Take a look at $enableCsrfValidation property of yii\web\Controller.

    Update:

    Here is some specification.

    If you want to disable CSRF validation for individual action(s) you need to do it in beforeAction event handler because CSRF token is checked before action runs (in beforeAction of yii\web\Controller).

    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {            
        if ($action->id == 'my-method') {
            $this->enableCsrfValidation = false;
        }
    
        return parent::beforeAction($action);
    }
    

    Official docs:

    • beforeAction()
    0 讨论(0)
  • 2020-11-27 16:59

    Put this inside your controller, just replace index with whatever action you want to disable csrf on.

    public function beforeAction()
    {      
        if ($this->action->id == 'index') {
            $this->enableCsrfValidation = false;
        }
        return true;
    }
    
    0 讨论(0)
  • 2020-11-27 17:12

    i have tried this and it worked .

    Go to the specific controller and write this at the top.

    public $enableCsrfValidation = false;
    
    0 讨论(0)
  • 2020-11-27 17:17

    For me this is what worked

    public function beforeAction($action) {
        if($action->id == 'my-action') {
            Yii::$app->request->enableCsrfValidation = false;
        }
        return parent::beforeAction($action);
    }
    
    0 讨论(0)
提交回复
热议问题