How to disable csrf for module?


#1

Hello,

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.

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;
	}


}

By the way, I’m using versioning, also added the same code in the module v1 file, but the same result.

I hope someone can help with this issue.

Thanks,


(Basil) #2

As far as i know, you can turn of csrf validation inside the controller, not the module.

see https://www.yiiframework.com/doc/api/2.0/yii-web-request#$enableCsrfValidation-detail