Home > Backend Development > PHP Tutorial > 400 error when POST data after enabling Csrf, csrfpost_PHP tutorial

400 error when POST data after enabling Csrf, csrfpost_PHP tutorial

WBOY
Release: 2016-07-13 09:47:20
Original
877 people have browsed it

400 error when POSTing data after enabling Csrf, csrfpost

I have been having this error recently, I have been looking for the reason, and I accidentally saw an article that solved it, and shared it with Let’s take a look.

The first solution is to turn off CSRf

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

The second solution is to add hidden fields to the form


The third solution is to add the _csrf field in AJAX

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

Yii matching process and Yii::$app->request->csrfToken value storage location description:

Storage Location

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

Verification method

  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

The above is the entire content of this article, I hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1027049.htmlTechArticleA 400 error occurs when POSTing data after enabling Csrf. csrfpost has been experiencing such errors recently, and I have been looking for the reason. I accidentally came across an article that solved the problem and wanted to share it with everyone. First...
Related labels:
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