Home >Backend Development >PHP Tutorial >400 error when POSTing data after enabling CSRF

400 error when POSTing data after enabling CSRF

WBOY
WBOYOriginal
2016-07-25 08:45:01776browse

I've been having this kind of error recently, and I've been looking for the cause. I came across an article that solved it, and I'd like to share it with you.

The first solution is to turn off CSRF

  1. public function init(){
  2. $this->enableCsrfValidation = false;
  3. }
Copy code

The second solution is to add hidden fields to the form


The third solution is to add the _csrf field in AJAX

  1. var csrfToken = $('meta[name="csrf-token"]').attr("content");
  2. $.ajax({
  3. type: 'POST',
  4. url: url,
  5. data: {_csrf:csrfToken},
  6. success: success,
  7. dataType: dataType
  8. });
Copy code

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

Storage location

  1. protected function createCsrfCookie($token)
  2. {
  3. $options = $this->csrfCookie;
  4. $options['name'] = $this->csrfParam;
  5. $options['value'] = $token;
  6. return new Cookie($options);
  7. }
Copy code

Verification method

  1. public function validateCsrfToken($token = null)
  2. {
  3. $method = $this->getMethod();
  4. // only validate CSRF token on non-"safe" methods http://www.w3 .org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
  5. if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
  6. return true;
  7. }
  8. $trueToken = $this->loadCsrfToken();
  9. if ($token !== null) {
  10. return $this->validateCsrfTokenInternal($token, $trueToken);
  11. } else {
  12. return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
  13. || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $ trueToken);
  14. }
  15. }
Copy code

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

Csrf, POST


Statement:
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