You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.
Hello Yii friends
I am going to write an article. Many times we write same code on every ajax call, but writing a single code in one controller is sufficient in ajax post with csrf security which is very easy.
At first go to components and open the controller.php
Simply add the following code:
// this function will be initialize in every controller call which will call initAjaxCsrfToken function
public function init() {
parent::init();
$this->initAjaxCsrfToken();
}
// this function will work to post csrf token.
protected function initAjaxCsrfToken() {
Yii::app()->clientScript->registerScript('AjaxCsrfToken', ' $.ajaxSetup({
data: {"' . Yii::app()->request->csrfTokenName . '": "' . Yii::app()->request->csrfToken . '"},
cache:false
});', CClientScript::POS_HEAD);
}
Enjoy coding
@robregonm
I didn't get the exact usage of this wiki article . Please explain!
huh
This is an global ajax option but not required.
Yii automatically insert csrf token into forms wheen csrf validation is enabled.
<form id="formID"......><input type="hidden" name="csrfToken" value="...."></form>
$.ajax({ url: 'xyz', data: $('#formID').serialize(), /*this store required csrf token because is in form hidden field. */ });
There is security issue with proposed solution
CSRF must be provided only for POST requests. If you also add CSRF token to GET requests it can be exposed and/or logged in log files which may be a security hole. CSRF token must be kept private...
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.