Home  >  Article  >  Backend Development  >  Solve the problem of 400 error after enabling CSRF

Solve the problem of 400 error after enabling CSRF

*文
*文Original
2017-12-27 11:43:242225browse

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;
}

The second solution is to add a hidden field to the form

00b5d82ce34774ecc2f284f6ef3a9154request->csrfToken ?>">

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
});

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);
  }

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);
    }
  }

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!

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