Solve the problem of 400 error after enabling CSRF

*文
Release: 2023-03-18 16:02:01
Original
2224 people have browsed it

How to solve the 400 error after enabling CSRF? This article mainly introduces the relevant information about the 400 error that occurs when POSTing data after enabling Csrf. I hope to be helpful.

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

The first solution is to turn off Csrf

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

The second solution is to add a hidden field 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

The matching process of Yii and Yii::$app-> ;request->csrfToken Description of the storage location of this value:

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

Related recommendations:

Explanation of knowledge points about the same-origin policy and csrf security policy

Detailed introduction to XSS and CSRF

Yii2.0 defense against csrf attack method

The above is the detailed content of Solve the problem of 400 error after enabling CSRF. For more information, please follow other related articles on the PHP Chinese website!

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