Yii2 默认是启用CSRF令牌验证,解决办法有如下三种:
第一种:配置在main.php中:
'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation 'enableCookieValidation' => true, 'cookieValidationKey' => 'cookvalid', ],
若要取消CSRF验证有两种方法
1. 在要取消的控制器中添加:
public $enableCsrfValidation = false;
2. 在配置中取消enableCookieValidation的验证
'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation 'enableCookieValidation' => false, 'cookieValidationKey' => 'cookvalid', ],
第二种:是在form表单中加入隐藏域
<input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">
第三种:在AJAX中加入_csrf字段
var csrfToken = $('meta[name="csrf-token"]').attr("content"); $.ajax({ type: 'POST', url: url, data: {_csrf:csrfToken}, success: success, dataType: dataType });