Commit 4f555a57 by Qiang Xue

Fixed CSRF validation bug.

parent f9b95755
...@@ -73,7 +73,10 @@ class Controller extends \yii\base\Controller ...@@ -73,7 +73,10 @@ class Controller extends \yii\base\Controller
public function beforeAction($action) public function beforeAction($action)
{ {
if (parent::beforeAction($action)) { if (parent::beforeAction($action)) {
return !$this->enableCsrfValidation || Yii::$app->getRequest()->validateCsrfToken(); if ($this->enableCsrfValidation && !Yii::$app->getRequest()->validateCsrfToken()) {
throw new HttpException(400, Yii::t('yii', 'Unable to verify your data submission.'));
}
return true;
} else { } else {
return false; return false;
} }
......
...@@ -1023,12 +1023,12 @@ class Request extends \yii\base\Request ...@@ -1023,12 +1023,12 @@ class Request extends \yii\base\Request
* The method will compare the CSRF token obtained from a cookie and from a POST field. * The method will compare the CSRF token obtained from a cookie and from a POST field.
* If they are different, a CSRF attack is detected and a 400 HTTP exception will be raised. * If they are different, a CSRF attack is detected and a 400 HTTP exception will be raised.
* This method is called in [[Controller::beforeAction()]]. * This method is called in [[Controller::beforeAction()]].
* @throws HttpException if the validation fails * @return boolean whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true.
*/ */
public function validateCsrfToken() public function validateCsrfToken()
{ {
if (!$this->enableCsrfValidation) { if (!$this->enableCsrfValidation) {
return; return true;
} }
$method = $this->getMethod(); $method = $this->getMethod();
if ($method === 'POST' || $method === 'PUT' || $method === 'PATCH' || $method === 'DELETE') { if ($method === 'POST' || $method === 'PUT' || $method === 'PATCH' || $method === 'DELETE') {
...@@ -1047,10 +1047,9 @@ class Request extends \yii\base\Request ...@@ -1047,10 +1047,9 @@ class Request extends \yii\base\Request
$token = $this->getDelete($this->csrfVar); $token = $this->getDelete($this->csrfVar);
} }
$valid = !empty($token) && $token === $trueToken || $this->getCsrfTokenFromHeader() === $trueToken; return !empty($token) && $token === $trueToken || $this->getCsrfTokenFromHeader() === $trueToken;
if (!$valid) { } else {
throw new HttpException(400, Yii::t('yii', 'Unable to verify your data submission.')); return true;
}
} }
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment