Disable CSRF validation for individual actions in

2020-01-25 06:01发布

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 classes, that are intended to be injected into controllers. I can't pass csrf validation token into the AJAX request because the thing I'm working with is external (made not by me) WYSIWYG plugin at the frontend. Yes, I can still disable csrf validation of the whole controller using these actions, but it may be insecure.

标签: csrf yii2
4条回答
▲ chillily
2楼-- · 2020-01-25 06:35

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:

查看更多
一纸荒年 Trace。
3楼-- · 2020-01-25 06:40

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;
}
查看更多
乱世女痞
4楼-- · 2020-01-25 06:45

For me this is what worked

public function beforeAction($action) {
    if($action->id == 'my-action') {
        Yii::$app->request->enableCsrfValidation = false;
    }
    return parent::beforeAction($action);
}
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-01-25 07:01

i have tried this and it worked .

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

public $enableCsrfValidation = false;
查看更多
登录 后发表回答