Yii CSRF disable for action

Asked
Active3 hr before
Viewed126 times

6 Answers

actiondisable
90%

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)., This disables CSRF validation for ALL actions in the controller. OP asked about individual actions. – Sarke May 25 at 8:03 ,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.

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;

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);
}
load more v
88%

For the specific controller / actions you can disable CSRF validation like so:,Take a look at $enableCsrfValidation property of yii\web\Controller.,Put this inside your controller, just replace index with whatever action you want to disable csrf on.,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).

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

use Yii;

...

Yii::$app - > controller - > enableCsrfValidation = false;
load more v
72%

I need to disable the CSRF for the whole API module, the module namespace is ‘app\modules\api’. I added in api.php ‘public $enableCsrfValidation = false;’, did not worked.,As far as i know, you can turn of csrf validation inside the controller, not the module.,More Learn Books Resources Develop Download Yii Report an Issue Report a Security Issue Contribute to Yii About What is Yii? Release Cycle News License Team Official logo,see https://www.yiiframework.com/doc/api/2.0/yii-web-request#$enableCsrfValidation-detail

here is the code:

namespace app\ modules\ api;

/**
 * api module definition class
 */
class Api extends\ yii\ base\ Module {
   /**
    * {@inheritdoc}
    */
   public $controllerNamespace = 'app\modules\api\controllers';
   public $enableCsrfValidation = false;

   /**
    * {@inheritdoc}
    */
   public
   function init() {
      parent::init();

      $ApiConfig = [
         'components' => [
            'errorHandler' => [
               //'class' => 'yii\web\ErrorHandler',
               'class' => yii\ web\ ErrorHandler::class,
               'errorAction' => 'api/v1/default/error'
            ],
            'request' => [
               'class' => \yii\ web\ Request::class,
               'cookieValidationKey' => 'xx2QZdKBHravCmHvTOnUzRvThAR8PbPV42',
               'parsers' => [
                  'application/json' => 'yii\web\JsonParser',
               ],
               'enableCsrfValidation' => false,
               'enableCookieValidation' => false,
            ],
            'response' => [
               'class' => \yii\ web\ Response::class,
               'format' => \yii\ web\ Response::FORMAT_JSON,
               'charset' => 'UTF-8',
            ],
         ],
         'bootstrap' => [
            [
               'class' => 'yii\filters\ContentNegotiator',
               'formats' => [
                  'application/json' => \yii\ web\ Response::FORMAT_JSON,
               ],
               ['log'],

            ],
         ],
      ];
      if (YII_ENV_DEV) {
         $ApiConfig['bootstrap'][] = 'debug';
         $ApiConfig['modules']['debug'] = [
            'class' => 'yii\debug\Module'
            // uncomment the following to add your IP if you are not connecting from localhost.
            // 'allowedIPs' => ['127.0.0.1', '::1'],
         ];

         $ApiConfig['bootstrap'][] = 'gii';
         $ApiConfig['modules']['gii'] = [
            'class' => 'yii\gii\Module'
            // uncomment the following to add your IP if you are not connecting from localhost.
            // 'allowedIPs' => ['127.0.0.1', '::1'],
         ];
      }\
      Yii::configure(\Yii::$app, $ApiConfig);
      // initialize the module with the configuration loaded from config.php
      //\Yii::configure($this, require __DIR__ . '/config.php');

      $handler = new\ yii\ web\ ErrorHandler(['errorAction' => 'api/v1/default/error']);\
      Yii::$app - > set('errorHandler', $handler);
      $handler - > register();
   }

   public
   function beforeAction($action) {
      //$e = \Yii::$app->getErrorHandler();
      //\Yii::error(print_r($e), "test_app");
      //return parent::beforeAction($action); // TODO: Change the autogenerated stub
      if (parent::beforeAction($action)) {

      }
      return true;
   }

}
65%

This code will run before beforeAction() of yii\base\Controller and yii\web\Controller.,Also it won't affect other actions, init() runs only if this particular standalone action is requested.,Currently it's calling module's beforeAction then controller's beforeAction where CSRF token is validated then it calls beforeRun of the action itself.,But it takes no effect and seems the only way to do this is to use Controller::beforeAction(), but it wisely to have an ability to manage csrf validation in Action::beforeRun() for my opinion, since it is called "standalone" action.

protected
function beforeRun() {
   \
   Yii::$app - > controller - > enableCsrfValidation = false;
   return true;
}
load more v
75%

For the specific controller / actions you can disable CSRF validation like so:,Take a look at $enableCsrfValidation property of yiiwebController.,Is there a way to disable CSRF validation for some actions of the controller keeping it enabled for the other ones?,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 yiiwebController).

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;

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 yiiwebController).

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

   return parent::beforeAction($action);
}
load more v
40%

class MyController extends Controller { public $enableCsrfValidation = false;

< ? 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();
   }
}
load more v

Other "action-disable" queries related to "Yii CSRF disable for action"