21
votes

I'm having problem with CSRF Validation in yii2. The validation works fine with the default form generated by the gii but when I edit the form with html tags then the form submission throws a bad request error. I have disabled csrf validation to hide the error but I want to use this for the security of the application and data validation.

Is there any way of solving this error or is there a way of configuring it to work correctly in this scenario?

2
Without seeing the code it's hard to assume what can cause this problem. Please add form changes that broke CSRF validation.arogachev
<form id="w0" class="form-horizontal" action="/pofil/backend/deposit/create" method="post" enctype="multipart/form-data"> <input type="hidden" name="_csrf" value="Ry1JRjA3QnouHC8IegZ1Pgp1LQV9XDcpGAADIF5WATAuYAwnYQAhLQ=="> <div class="form-group field-page-title required"> <label class="control-label col-sm-1" for="page-title">Title</label> <div class="col-sm-11"> <input type="text" id="page-title" class="form-control" name="Page[title]" maxlength="500"> </form>msucil
Please update your question instead of posting it as comment,arogachev

2 Answers

44
votes

I guess, your html form doesn't have hidden _csrf field, which is automatically generated by standard Yii2 widgets.

So the minimum code of your custom form might be like this:

<form method="post">
    <input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />
    <button type="submit"> Save </button>
</form>
5
votes

Try this

<?=yii\helpers\Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken)?>