Home > Backend Development > PHP Tutorial > 启用Csrf后POST数据时出现的400错误_PHP

启用Csrf后POST数据时出现的400错误_PHP

WBOY
Release: 2016-05-30 08:45:34
Original
1319 people have browsed it

最近一直出现这样的错误,一直在查找原因,偶然看到一篇解决的文章,分享给大家看看。

第一种解决办法是关闭Csrf

public function init(){
  $this->enableCsrfValidation = false;
}
Copy after login

第二种解决办法是在form表单中加入隐藏域


第三种解决办法是在AJAX中加入_csrf字段

var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
 type: 'POST',
 url: url,
 data: {_csrf:csrfToken},
 success: success,
 dataType: dataType
});
Copy after login

Yii这个匹配的过程和Yii::$app->request->csrfToken 这个值存储位置说明:

存储位置

  protected function createCsrfCookie($token)
  {
    $options = $this->csrfCookie;
    $options['name'] = $this->csrfParam;
    $options['value'] = $token;
    return new Cookie($options);
  }
Copy after login

校验方法

  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);
    }
  }
Copy after login

以上所述就是本文的全部内容了,希望大家能够喜欢。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template