Yii2 validateCsrfToken does not work as expected

465 views Asked by At

I have the following create action that has two ways to be accessed, one via AJAX and the other ordinary way:

public function actionCreate()
    {
        if (Yii::$app->request->isAjax && Yii::$app->request->validateCsrfToken(Yii::$app->request->post('csrf', 'falsesds'))){

          \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
      return [
          'search' => Yii::$app->request->getCsrfToken(),
          'code' => 100,
      ];
    }
        $model = new Statics();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

I'm sure that there is no any parameter sent to the action named csrf with the value of csrf token generated in the source page. inspite of the described, the AJAX request always run perfectly, i.e there is a JSON response with the search key. The following is the Jquery AJAX code that I have used:

$(document).ready(function(){
  var csrfToken = $('meta[name="csrf-token"]').attr("content");
  $(".addContent").click(function(event){   
    event.preventDefault();
    $.ajax(this.href,{
      data:{
        'path': getParameterByName('path', this.href),
        'position': getParameterByName('position', this.href)
      },
      type: 'POST',
      success: function(data){
        alert(data.search+"\n\n"+csrfToken);
      },
      error: function(data){
        alert('bad');
      }
    });
  });
});

I want to secure this process and I don't know how to use Yii2 CSRF token to do that. In other words, I want to prevent any modification to the posted parameters, i.e path and position.

1

There are 1 answers

0
Tony On

Actually csrf token has nothing to do with submitted data correctness, which you want to achieve, as I can understand from your question. It only can guarantee that the data is submitted from safe place and can be processed. Consider using some type of hash to check that there is no modification in posted parameters.