Yii中ajax提交注意事項

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
        ],
]


1.2  form中的csrf


在使用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');



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章