3.6 版本发布请求中的 CSRF 令牌不匹配 [英] CSRF token mismatch in post request in 3.6 version

查看:22
本文介绍了3.6 版本发布请求中的 CSRF 令牌不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的 cakephp 应用程序.一个是 3.5 版,另一个是 3.6 版.

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

当我使用和构建 3.5 应用程序时,我没有遇到 CSRF 在 post 请求中匹配的问题. 但是现在当我使用 3.6 时,它给了我 CSRF 令牌错误.

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.

虽然在两个应用的AppController中,CSRF组件都被禁用了.

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?

推荐答案

最新的 3.6 应用程序模板现在默认使用 CSRF 中间件,请参阅您的应用程序 src/Application.php 文件.不幸的是,这种变化没有被正确记录下来,让人们措手不及.

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.

理想情况下,您不要禁用它,而是将正确的 CSRF 令牌与您的 AJAX 请求一起传递,您可以轻松地从视图模板中的请求对象中获取令牌,例如在布局中使其全局可用:

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>

然后您可以在 AJAX 请求中轻松使用它:

You can then easily use it in your AJAX requests:

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

另见

这篇关于3.6 版本发布请求中的 CSRF 令牌不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆