Let me see
Let me see

Reputation: 5094

Csrftoken not validating in case of deleting the records in yii

I am learning Yii and i am trying csrf validation I have made the following class in the application.components.HttpRequest

class HttpRequest extends CHttpRequest {

    private $_csrfToken;

    public function getCsrfToken() {
        if($this->_csrfToken === NULL) {
            $this->_csrfToken=  sha1(uniqid(mt_rand(),true));

            if(!isset(Yii::app()->session['_tokenforcsrf'])) {
                Yii::app()->session['_tokenforcsrf']=  $this->_csrfToken;
            } else {
                Yii::app()->session['_tokenforcsrf']=  $this->_csrfToken;
            }

            return $this->_csrfToken;
        }
    }

    public function validateCsrfToken($event) {
        if($this->getIsPostRequest()) {
            if(isset(Yii::app()->session['_tokenforcsrf']) && isset($_POST['_tokenforcsrf'])) {
                $sessiontoken=Yii::app()->session['_tokenforcsrf'];
                $posttoken=$_POST['_tokenforcsrf'];

                if($sessiontoken === $posttoken) {
                    $validity=TRUE;
                } else {
                    $validity=FALSE;
                }

            } else {
                $validity=false;
            }

            if($validity==false) {
                throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
            }

        }
        parent::validateCsrfToken($event);
    }
}

The csrf validation is working properly in case of everything but whenever i try to delete some thing it shows that The CSRF token could not be verified Its not validating in case of deletion of the records.

The link from where i am trying to delete is

 $this->menu = [
    [
        'label' => 'List Rolearea',
        'url' => ['index']
    ],
    [
        'label' => 'Create Rolearea', 
        'url' => ['create']
    ],
    [
        'label' => 'Update Rolearea', 
        'url' => [
            'update', 
            'owner'=>$model->roleName
        ]
    ],
    [
        'label' => 'Delete Rolearea', 
        'url' => '#', 
        'linkOptions' => [
            'submit' => [
                'delete',
                'id' => $model->roleNo
            ],
            'confirm' => 'Are you sure you want to delete this item?'
        ]
    ],
    [
        'label' => 'Manage Rolearea',
        'url' => ['admin']
    ],
];

So my question is how can i resolve the issue of csrf validation in this case??

Upvotes: 0

Views: 243

Answers (1)

DaSourcerer
DaSourcerer

Reputation: 6606

Your code requires that every action that has been secured via your CSRF token has to be invoked via POST. A simple link will result into a GET request, which is why your validation fails.

Upvotes: 1

Related Questions