啟用Csrf后POST數(shù)據(jù)時出現(xiàn)的400錯誤
最近一直出現(xiàn)這樣的錯誤,一直在查找原因,偶然看到一篇解決的文章,分享給大家看看。
第一種解決辦法是關(guān)閉Csrf
public function init(){
$this->enableCsrfValidation = false;
}
第二種解決辦法是在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
});
Yii這個匹配的過程和Yii::$app->request->csrfToken 這個值存儲位置說明:
存儲位置
protected function createCsrfCookie($token)
{
$options = $this->csrfCookie;
$options['name'] = $this->csrfParam;
$options['value'] = $token;
return new Cookie($options);
}
校驗方法
public function validateCsrfToken($token = null)
{
$method = $this->getMethod();
// only validate CSRF token on non-"safe" methods http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
return true;
}
$trueToken = $this->loadCsrfToken();
if ($token !== null) {
return $this->validateCsrfTokenInternal($token, $trueToken);
} else {
return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
|| $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
}
}
以上所述就是本文的全部內(nèi)容了,希望大家能夠喜歡。
相關(guān)文章
PHP字符過濾函數(shù)去除字符串最后一個逗號(rtrim)
PHP字符過濾函數(shù)去除字符串最后一個逗號,用php自帶的函數(shù)比較容易解決2013-03-03
php str_replace替換指定次數(shù)的方法詳解
本篇文章主要介紹了php str_replace替換指定次數(shù)的方法,具有很好的參考價值。下面跟著小編一起來看下吧2017-05-05
PHP實現(xiàn)負(fù)載均衡session共享redis緩存操作示例

