Yii 2.0 CSRF Validation for AJAX Request

I have an ajax function that starts deleting a record from my database.

I need to do a CSRF check for the same. How can i do this?

I am sending a CSRF cookie along with my mail request, but Yii 2.0 does not validate it, and any input that is passed through ajax reaches the server.

How to do CSRF validation for ajax requests.

Do we need to manually set cookies and check?

+7
php yii2 csrf
source share
2 answers

You do not need to set cookies manually.

If you use jQuery, the CSRF token will be sent automatically.

For example, for AngularJS, you can add it manually to request the following parameters:

 yii.getCsrfParam(): yii.getCsrfToken() 

Make sure you have YiiAsset .

Otherwise, you can get them from the meta tags (basically what these two methods do):

 $('meta[name=csrf-param]').prop('content'): $('meta[name=csrf-token]').prop('content') 

Also note that to enable CSRF checking, the Controller property and Request property enableCsrfValidation must be set to true .

Update:

Another important thing to understand:

CSRF token will be checked only by these methods: GET , HEAD , OPTIONS .

Also make sure the main layout has <?= Html::csrfMetaTags ?> .

+3
source share

Finally, I determined that just turning on

  <?= Html::csrfMetaTags() ?> 

in the mail layout will automatically add csrf confirmation for each message / receive requests whether it is ajax or not. We do not need to manually send the csrf token with aja

  <?= Html::csrfMetaTags() ?> 

the request fails and throws an exception. So that was my mistake. Just add <?= Html::csrfMetaTags() ?>

will perform a csrf check regardless of whether it is ajax or an uniaxial request / form.

Yii 2.0 inventor hats for such awesome stuff # love-yii-2.0

0
source share

All Articles