CSRF token mismatch in post request in 3.6 version

后端 未结 4 664
别那么骄傲
别那么骄傲 2020-12-10 19:19

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 requ

相关标签:
4条回答
  • 2020-12-10 19:40

    For CakePHP 3.8, this worked for me. In config\routes.php comment the line as so :

    //$routes->applyMiddleware('csrf');
    
    0 讨论(0)
  • 2020-12-10 19:42

    Add this code on your $.ajax() function call:

    beforeSend: function (xhr) { // Add this line
            xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
     },  // Add this line
    
    0 讨论(0)
  • 2020-12-10 19:46

    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

    • Cookbook > Middleware > Cross Site Request Forgery (CSRF) Middleware
    • Cookbook > Middleware > CSRF Protection and AJAX Requests
    0 讨论(0)
  • 2020-12-10 19:59

    i had the same error, without using ajax, the problem was that admin theme was not using cakephp 3 form helper sintax, it was html.

    after i changed with Form->create() ?> Form->end() ?> it worked fine

    0 讨论(0)
提交回复
热议问题