Csrf Protection


i already add


in main config file, but all my post method in jquery call won’t work, and i can’t get the value !!!

what is the problem/ solution ??

warm regards

Make sure you are sending csrf token (either as hidden field or by supplying additional data to ajax request).

Otherwise you’ll get 403.

thanks for your quick respond

but why in regular getting post value i am getting values, but only problem with ajax post

If you check the generated HTML output in a standard CActiveForm, you’ll notice that there’s a hidden field containing a hidden CSRF token. In regular posts, all the form data are sent, but in Ajax requests, it depends on what you send.

In my main function i enabled the


. How can i check that csrf validation is working or not??

In the case of Ajax post i am sending the csrf token then also am not able get the value in my Ajax calling function.

Please post the relevant parts of your view and controller

thanks to all,

i implement it , and i overwrite 2 function for comparing in component

Good to hear that it works for you but it would be nice if you can share your solution here so it may help others in the future with similar problem.

sorry for delay , i was in vacation :)

fist i create one class and extent it to CHttpRequest

class HttpRequest extends CHttpRequest{

private $_csrfToken;


	public function getCsrfToken()




			$session = Yii::app()->session;




				$csrfToken = sha1(uniqid(mt_rand(),true));

				$session->add($this->csrfTokenName, $csrfToken);


			$this->_csrfToken = $csrfToken;



		return $this->_csrfToken;


	public function validateCsrfToken($event)




			// only validate POST requests


			if($session->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName]))









				throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));




and save this file as HttpRequest.php in component folder,

then in config/main do this:







and for ajax request i just post the token value and by default Yii validate it,

if you are using Get method you should manually validate it.

an another benefit of this class is using validation with session,

i follow this article:


When you said “and for ajax request i just post the token value and by default Yii validate it,”
What was the key/value you posted?

How to use this with CDBSession?

I want to use it CDBHttpSession, strange enough, the httprequest class created above, doesn’t use the cdbhttpsession if configured the following way.

'session' => array(

	'class' => 'CDbHttpSession',
	'cookieParams' => array(
		'domain' => $_SERVER['HTTP_HOST'],
		//'path' => '/; samesite=Strict',
		'secure' => true,
		'httponly' => true
	'connectionID' => 'db',
	'autoCreateSessionTable' => false,

It just throws 400 bad request

Error Code:400

The CSRF token could not be verified.

No sure how to make the above class access the cdbhttpsession