Tuesday 27 January 2015

Yii2: Using csrf token

First, if you do not understand what is the CSRF token? and why should we use it, please refer to the following link :
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)

One of the new features of Yii2 is CSRF validation enabled by default.
If you use ajax or basic form as follows :

<form action='#' method='POST'>
    ...........
</form>

You will get an error exception :

Bad Request (#400): Unable to verify your data submission

That is because you do not submit csrf token. The easiest way if you dont care about csrf just disable it in main config :

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

Or in Controller :

public function beforeAction($action) {
    $this->enableCsrfValidation = false;
    return parent::beforeAction($action);
}

So how to use Csrf Validation for your strong security website:

* With basic form:
- Create form with yii\widgets\ActiveForm or yii\bootstrap\ActiveForm
ActiveForm will automatically add a token in the form

Can use like this

<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    ....
<?php ActiveForm::end(); ?>

Or

<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
      <input type='text' name='name'/>
      .........
<?php ActiveForm::end(); ?>

* With manual form:
you must manually add CSRF token in the form

<form action='#' method='POST'>
   <input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
   ....
</form>

* With Ajax
- In main layout add csrfMetaTags :
<head>
   .......
   <?= Html::csrfMetaTags() ?>
</head>

- And in javascript ajax code add csrf param like this:

var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
         url: 'request',
         type: 'post',
         dataType: 'json',
         data: {param1: param1, _csrf : csrfToken},
});

10 comments:

  1. Thanks very much. This is the one solution Im looking for.

    ReplyDelete
  2. thanks for this solution

    ReplyDelete
  3. Thanks, exactly what I needed!

    ReplyDelete
  4. ajax not working with type : 'post' but working on 'get', why

    ReplyDelete
  5. Great post!

    It is very informative and helpful code of csrf token

    ReplyDelete
  6. Great Info! Thanks.

    ReplyDelete
  7. Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!

    ReplyDelete