Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle CSRF Validation in Yii2 Framework?

Tags:

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?

like image 771
msucil Avatar asked Feb 12 '15 09:02

msucil


People also ask

How to validate CSRF token Yii2?

'components' => array( 'request' => array( 'enableCsrfValidation' => true, ), ), Note: When you ebable CSRF validation and use form builder to generate a form(only post), Yii will auto generate a hidden field and put it in the form, at the same time, Yii will create a cookie with CSRF token.

What is CSRF token in yii2?

Cross-site request Forgery (CSRF) is one of a typical web application vulnerabilities. It's based on the assumption that user may be authenticated at some legitimate website.

How is CSRF token validation?

When a CSRF token is generated, it should be stored server-side within the user's session data. When a subsequent request is received that requires validation, the server-side application should verify that the request includes a token which matches the value that was stored in the user's session.


2 Answers

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> 
like image 178
Pavel Bariev Avatar answered Sep 30 '22 20:09

Pavel Bariev


Try this

<?=yii\helpers\Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken)?> 
like image 30
Alex S Avatar answered Sep 30 '22 22:09

Alex S