Yii中ajax提交注意事项

10 篇文章 0 订阅
10 篇文章 0 订阅

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');



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值