PHP, Yii Framework

Disable Yii2 CSRF on Specific Actions

<?php

namespace common\components;

use Yii;

class Request extends \yii\web\Request
{
    public $noCsrfRoutes = [];

    public function validateCsrfToken()
    {
        if (
            $this->enableCsrfValidation &&
            in_array(Yii::$app->getUrlManager()->parseRequest($this)[0], $this->noCsrfRoutes)
        ) {
            return true;
        }
        return parent::validateCsrfToken();
    }
}

Then, add the request component to your configuration like so:

'request' => [
    'class' => 'common\components\Request',
    'noCsrfRoutes' => [
        'order/calculate-ns-shipping'
    ]
],
Advertisements

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()
    {
    parent::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:

WordPress.com Logo

You are commenting using your WordPress.com 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