Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii 2.0 CSRF validation for AJAX request

Tags:

php

csrf

yii2

I have an ajax function that triggers an entry deletion from my database.

I need to do CSRF validation for the same. How can I do that?

I am sending the CSRF cookie along with my post request, but Yii 2.0 is not validating it and any input that is passed through ajax is reaching the server.

How do I do CSRF validation for ajax requests.

Whether we need to manually set cookie and check?

like image 672
Jinu Joseph Daniel Avatar asked May 10 '15 16:05

Jinu Joseph Daniel


2 Answers

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.

like image 115
arogachev Avatar answered Nov 16 '22 07:11

arogachev


Please let me add some optional answer i found at this page,

    <head>
       .......
       <?= Html::csrfMetaTags() ?>
    </head>
    .......
<script>
    var csrfToken = $('meta[name="csrf-token"]').attr("content");
    $.ajax({
             url: 'request',
             type: 'post',
             dataType: 'json',
             data: {param1: param1, _csrf : csrfToken},
    });
</script>
like image 1
24 revs, 19 users 31% Avatar answered Nov 16 '22 07:11

24 revs, 19 users 31%