启用Csrf后POST数据时出现的400错误
最近一直出现这样的错误,一直在查找原因,偶然看到一篇解决的文章,分享给大家看看。
第一种解决办法是关闭Csrf
publicfunctioninit(){
$this->enableCsrfValidation=false;
}
第二种解决办法是在form表单中加入隐藏域
<inputname="_csrf"type="hidden"id="_csrf"value="<?=Yii::$app->request->csrfToken?>">
第三种解决办法是在AJAX中加入_csrf字段
varcsrfToken=$('meta[name="csrf-token"]').attr("content");
$.ajax({
type:'POST',
url:url,
data:{_csrf:csrfToken},
success:success,
dataType:dataType
});
Yii这个匹配的过程和Yii::$app->request->csrfToken这个值存储位置说明:
存储位置
protectedfunctioncreateCsrfCookie($token)
{
$options=$this->csrfCookie;
$options['name']=$this->csrfParam;
$options['value']=$token;
returnnewCookie($options);
}
校验方法
publicfunctionvalidateCsrfToken($token=null)
{
$method=$this->getMethod();
//onlyvalidateCSRFtokenonnon-"safe"methodshttp://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
if(!$this->enableCsrfValidation||in_array($method,['GET','HEAD','OPTIONS'],true)){
returntrue;
}
$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);
}
}
以上所述就是本文的全部内容了,希望大家能够喜欢。