Yii 2.0 CSRF validation for AJAX request

雨燕双飞 提交于 2019-12-03 12:49:21

You don't need to manually set cookie.

If you are using jQuery CSRF token will be sent automatically.

For example for AngularJS you can add it manually to request params like that:

yii.getCsrfParam(): yii.getCsrfToken()

Make sure you have YiiAsset included.

Otherwise you can retrieve them from meta tags (that's basically what these two methods do):

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

Also note that for enabling CSRF validation both Controller's and Request's property enableCsrfValidation property must be set to true.

Update:

Another important thing to understand:

CSRF token will be validated only on this methods: GET, HEAD, OPTIONS.

Also make sure you have <?= Html::csrfMetaTags ?> in main layout.

Finally I identified that just including

    <?= Html::csrfMetaTags() ?>

in mail layout will automatically add csrf validation to every post / get requests whether it is ajax or not.We dont need to manually send csrf token along with aja

    <?= Html::csrfMetaTags() ?>

the request is failing and throwing the exception..So it was my mistake..Just adding <?= Html::csrfMetaTags() ?>

will do csrf validation whether it is ajax or non ajax request / form submission..

Hats off to Yii 2.0 inventors for such an awesome stuff #love-yii-2.0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!