CSRF validation with valums-ajax-upload

Hi all!

I try to use http://valums.com/ajax-upload/ with CSRF-validation, but receive "The CSRF token could not be verified." message.

I 've added YII_CSRF_TOKEN to ‘params’ array.

In AJAX request’s header I have:




Cookie	PHPSESSID=qkhigtapt6sddlodrepqai1np2; YII_CSRF_TOKEN=8a90886a92ae83e2b1044e5aa1c801154bfba7b7



In http request I have:




http://.../createAjax?YII_CSRF_TOKEN6=8a90886a92ae83e2b1044e5aa1c801154bfba7b7&qqfile=test.txt



If I switched off CSRF-validation it works fine.

Can any one help me to run CSRF with valums-ajax-upload? Have someone a good experience with that?

Thanks !

I’ve been trying to work this one out myself.

Somehow you need to the get the CSRF value posted with the form data (the uploads) as a hidden field.

In the earlier version of the upload script something like

data: { YII_CSRF_TOKEN : ‘<?php echo Yii::app()->request->getCsrfToken(); ?>’ }

might have worked but not in the current version.

Just read CSRF token from $_GET in this case :)

All you need - rewrite function validateCsrfToken in CHttpRequest class (create own class e.g. MyRequest extends CHttpRequest)…

struggling a bit with this.

In protected/components

I added a file ValidateCsrfByGet.php

with code…


class ValidateCsrfByGet extends CHttpRequest

{


	public function validateCsrfToken($event)

	{


	    if($this->getIsPostRequest())

	    {

	        // only validate POST requests

	        $cookies=$this->getCookies();

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

	        {

	            $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value;

	            $tokenFromPost=$_POST[$this->csrfTokenName];

	            $valid=$tokenFromCookie===$tokenFromPost;

	        }

	        else

	            $valid=false;

	        if(!$valid)

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

	    }

	} 

 

}

I was expecting to be able to make changes to this function and those to affect the CSRF check in any forms on the site. Even when I only have the throw exception line, no forms are affected.

Is this an inheritance thing?

EDIT: Answer here: http://www.yiiframework.com/forum/index.php?/topic/14500-re-writing-a-class-method-without-editing-framework-files/

In case anyone was looking for a clean solution to this problem, I forked file-uploader and added the ability to add POST key/value pairs. When creating your file uploader, set encoding to ‘multipart’, and pass in your CSRF token into multipartParams. It will arrive as a $_POST parameter and your CSRF protection will work as expected.

The forked version is available here: https://github.com/gtcode/file-uploader/blob/master/client/fileuploader.js