首页 > Web开发 > 详细

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

时间:2016-01-21 10:03:29      阅读:293      评论:0      收藏:0      [点我收藏+]

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

第一种解决办法是关闭Csrf

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

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

<input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">

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

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

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

存储位置

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

校验方法

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

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

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

原文:http://www.jb51.net/article/68946.htm

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!