PHP, Yii Framework

Disable Yii2 CSRF on specific actions

I needed to disable the Yii2 CSRF on specific actions recently, mainly due to the action being called from an external source.

What I did was extend the Request object like so:


namespace common\components;

use Yii;

class Request extends \yii\web\Request
	public $noCsrfRoutes = [];
	public function validateCsrfToken()
			$this->enableCsrfValidation && 
			in_array(Yii::$app->getUrlManager()->parseRequest($this)[0], $this->noCsrfRoutes)
			return true;
		return parent::validateCsrfToken();

and then added the request component to my config like so:

		'request' => [
			'class' => 'common\components\Request',
			'noCsrfRoutes' => [

And that works.


4 thoughts on “Disable Yii2 CSRF on specific actions

  1. There is a much quicker way of doing this in your controller.

    class MyController extends Controller
    public $enableCsrfValidation = false;


  2. I had to disable this csrf check in two actions. In controller
    public function init()
    $this->on(self::EVENT_BEFORE_ACTION, function(ActionEvent $event) {
    if (in_array($event->action->id, [‘save’, ‘load’])) {
    $this->enableCsrfValidation = false;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s