Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

cakephp - CSRF token mismatch in post request in 3.6 version

I have two different apps of cakephp. One has a version 3.5 and other 3.6.

When i used and built 3.5 app i did not have a problem of CSRF matching in post request. But now as i am using 3.6 it is giving me error of CSRF token.

Although in both app's AppController, CSRF component is disable.

//$this->loadComponent('Csrf');

i am using simple post request like this:

$.ajax({
        type: "POST",
        url: "../user/my_action",
        dataType: 'json',
        success: function (data) {
            set_data(data.response);
        }
    });

What am i missing? or some configuration i have done wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The latest 3.6 application template now uses the CSRF middleware by default, see your apps src/Application.php file. Unfortunately this change hasn't been documented properly, and hit people by surprise.

Ideally you do not disable it, but instead pass the proper CSRF token alongside with your AJAX requests, you can easily obtain the token from the request object in your view templates, for example in the layout to make it globally available:

<script>
var csrfToken = <?= json_encode($this->request->getParam('_csrfToken')) ?>;
// ...
</script>

You can then easily use it in your AJAX requests:

$.ajax({
    headers: {
        'X-CSRF-Token': csrfToken
    },
    // ...
});

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...