Browse Source

use meta tags to pass CSRF token.

tags/2.0.0-beta
Qiang Xue 11 years ago
parent
commit
1aa836ffc7
  1. 19
      framework/yii/assets/yii.js
  2. 8
      framework/yii/base/View.php
  3. 15
      framework/yii/web/YiiAsset.php

19
framework/yii/assets/yii.js

@ -43,12 +43,19 @@
*/
yii = (function ($) {
var pub = {
// version of Yii framework
version: '2.0',
// CSRF token name and value. If this is set and a form is created and submitted using JavaScript
// via POST, the CSRF token should be submitted too to pass CSRF validation.
csrfVar: undefined,
csrfToken: undefined,
/**
* @return string|undefined the CSRF variable name. Undefined is returned is CSRF validation is not enabled.
*/
getCsrfVar: function() {
return $('meta[name=csrf-var]').attr('content');
},
/**
* @return string|undefined the CSRF token. Undefined is returned is CSRF validation is not enabled.
*/
getCsrfToken: function() {
return $('meta[name=csrf-token]').attr('content');
},
initModule: function (module) {
if (module.isActive === undefined || module.isActive) {

8
framework/yii/base/View.php

@ -12,6 +12,7 @@ use yii\helpers\FileHelper;
use yii\helpers\Html;
use yii\web\JqueryAsset;
use yii\web\AssetBundle;
use yii\web\Request;
use yii\widgets\Block;
use yii\widgets\ContentDecorator;
use yii\widgets\FragmentCache;
@ -708,6 +709,13 @@ class View extends Component
if (!empty($this->metaTags)) {
$lines[] = implode("\n", $this->metaTags);
}
$request = Yii::$app->getRequest();
if ($request instanceof Request && $request->enableCsrfValidation) {
$lines[] = Html::tag('meta', '', array('name' => 'csrf-var', 'content' => $request->csrfVar));
$lines[] = Html::tag('meta', '', array('name' => 'csrf-token', 'content' => $request->getCsrfToken()));
}
if (!empty($this->linkTags)) {
$lines[] = implode("\n", $this->linkTags);
}

15
framework/yii/web/YiiAsset.php

@ -23,19 +23,4 @@ class YiiAsset extends AssetBundle
public $depends = array(
'yii\web\JqueryAsset',
);
/**
* @inheritdoc
*/
public function registerAssets($view)
{
parent::registerAssets($view);
$js[] = "yii.version='" . Yii::getVersion() . "';";
$request = Yii::$app->getRequest();
if ($request instanceof Request && $request->enableCsrfValidation) {
$js[] = "yii.csrfVar='{$request->csrfVar}';";
$js[] = "yii.csrfToken='{$request->csrfToken}';";
}
$view->registerJs(implode("\n", $js), View::POS_END);
}
}

Loading…
Cancel
Save