L.Nelson
L.Nelson

Reputation: 63

csrf validation in yii2 not working

I have enabled csrf validation as true in my controller.But after few minutes, while submitting the form,csrf token got expired and got bad request message,eventhough I am passing csrf token through ajax.Please provide me a solution to get over this issue.

Below is my sample code

Controller

 public function beforeAction($action) 
    {
      $this->enableCsrfValidation = true;
      return parent::beforeAction($action);
    }

JS page

  var csrfToken = $('meta[name="csrf-token"]').attr("content");

Ajax call

  var values = { 
      'id'       : id,
     'cpcode'   : cpcode,  
     '_csrf'    : csrfToken

   };  
   $.ajax({ 
     type      : 'POST', //Method type
     url       : baseurl +'/site/test', 
     data      : values, 
    dataType  : 'json',
    success   : function(data)
      {

      }
   }
 );

main.php

 <head> <?= Html::csrfMetaTags() ?></head>

Upvotes: 0

Views: 2827

Answers (2)

redflasher
redflasher

Reputation: 717

Try add header like this:

$.ajax({ 
...
headers: {'X-CSRF-Token':"U05vc3J6YmVmPgAaFh8gAiMvPBQTETMrBjc8JRA4GywBBwMGAzA7Og=="},
...
}

Upvotes: 1

Bizley
Bizley

Reputation: 18021

Shouldn't it be:

var values = { 
    'id': id,
    'cpcode': cpcode,  
    yii.getCsrfParam(): yii.getCsrfToken()
};  

Upvotes: 0

Related Questions