php 如何在 Yii2 框架中处理 CSRF 验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28473298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle CSRF Validation in Yii2 Framework?
提问by msucil
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.
我在 yii2 中遇到 CSRF 验证问题。验证与 gii 生成的默认表单一起工作正常,但是当我使用 html 标签编辑表单时,表单提交会引发错误的请求错误。我已禁用 csrf 验证以隐藏错误,但我想将其用于应用程序和数据验证的安全性。
Is there any way of solving this error or is there a way of configuring it to work correctly in this scenario?
有没有办法解决这个错误,或者有没有办法配置它在这种情况下正常工作?
回答by Pavel Bariev
I guess, your html form doesn't have hidden _csrf
field, which is automatically generated by standard Yii2 widgets.
我猜,您的 html 表单没有隐藏_csrf
字段,这是由标准 Yii2 小部件自动生成的。
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>
回答by Alex S
Try this
尝试这个
<?=yii\helpers\Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken)?>