Yii2 - how to disable CSRF token validation

  • Last update: Apr 3, 2024
  • Views: 36
  • Author: Admin
Yii2 - how to disable CSRF token validation

Colleagues hello to all.

In today's article, we'll talk about how you can disable CSRF token verification in Yii2. CSRF stands for cross-site request forgery when a request is sent on your behalf to a site of which you are a user. Just from such  attacks one of the options to protect against request forgery can be a special token that is generated in a string and sent along with the request. After sending a request to your server, this token is checked for validity. 

Checking the CSRF token is enabled by default.

If you send a normal HTML form or a normal AJAX request to the server, you will get an error - Bad Request (#400): Unable to verify your data submission. This error will always occur when submitting data the value of the CSRF token will not be sent to the server.

 

This is what your token will look like on the site.

yii2_disable_csrf_token

And every time the page is reloaded, this token will change.


 

The first option to disable checking CSRF token in Yii2 is at the level of some action. To do this, use the code below:

public function beforeAction($action)
{
    if (in_array($action->id, ['login'])) {
        $this->enableCsrfValidation = false;
    }
    return parent::beforeAction($action);
}

yii2_disable_csrf_token

In this option, the beforeAction method will always be called before all actions in this controller, and if any of the actions matches the login name, then verification of the  CSRF token for that action will be disabled.


 

There is another option that is suitable for those people who do not worry about the security of their application. Validation CSRF token can be disabled for the entire site at once, for this you need to add the  enableCsrfValidation parameter with a value of false in the web.php configuration file.

'request' => [
    'enableCsrfValidation' => false,
],

yii2_disable_csrf_token


 

Thank you all, I hope that my article helped you in some way.

 

SIMILAR ARTICLES