1 Yii中为了防止csrf攻击,封装了CSRF令牌。csrf都是由Yii::$app->request处理的。
1.1 YII框架安装默认开启了csrf验证,关闭验证的方法如下
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'o-WunMjhKD*******h56gbenoLEfmqp',
'enableCsrfValidation' => false, //需要验证的时候改为true即可,默认为true
],
]
在使用ActiveForm post提交表单时,会自动在表单添加隐藏的crsf字段
<form id="w0" class="form-horizontal" action="a.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="_csrf" value="NHRjMWF1WkZ6QQRLPiwKIRlEMnAlAmkNXT8RU1JEbiBVFTxQVwUzEA=="><span style="font-family: Arial, Helvetica, sans-serif;"></form></span>
也就是说如果form表单是你自己用html写的,则要在表单中添加隐藏csrf元素,一般检验不通过报400的错误。
<input type="hidden" name="_csrf" value=" <?= Yii::$app->request->csrfToken ?>">
//name值也可以写成<?= Yii::$app->request->csrfParam?>,这样写可以避免request被重定义后,_csrf被改为其他值后的问题。
1.3 head中的csrf
<?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
/* @var $this \yii\web\View */
/* @var $content string */
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<strong> <?= Html::csrfMetaTags() ?></strong>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= $content ?>
</div>
</div>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
1.4 ajax中的csrf
<script>
$.post("<?= Yii::$app->urlManager->createUrl(['aa/record'])?>",
res = {
_csrf: yii.getCsrfToken(), //或者 _csrf: '<?= Yii::$app->request->csrfToken ?>',
errMsg:"addCard:fail",
cardList:
[{
cardId: "pAuXZji09Kc-K8MBCBcGgXDfdUZ0",
cardExt: '{"code": "123","timestamp": "1422359207", "signature":"fgdfgdfdhhg"}',
isSuccess:"false"
}]
},
function(data){
// alert("Data: " + data);
});
alert(JSON.stringify(res));
</script
或者直接调用头部中的csrf
$('meta[name=csrf-token]').attr('content');