CakePHP 3.7.3: Use SecurityComponent with Ajax with SPA

最后都变了- 提交于 2019-12-07 22:02:51

问题


This is a classic issue with ajax request with enabled SecurityComponent. I have mainly a SPA. That's the main problem.

I'm using also the CSRF component, which works fine:

const response = await axios.post("/items/add.json", data, {
  headers: {"X-CSRF-Token": "<?= $this->getRequest()->getParam('_csrfToken') ?>"}
});

What doesnt work is to send the _Token for the security component:

{message: "'_Token' was not found in request data.", url: "/.../add.json", code: 400,…}

Of course I can disable the SecurityComponent.

I don't need a form/form-helper for my request, then the question is if it makes sense to use the SecurityComponent at all here when I don't use a traditional form based application. Of course it makes sense that I expect certain post fields/values in certain actions but I'm not sure how to use that in conjunction with the SecurityComponent.

I guess I could create a dummy form with the helper and extract the tokens from there, but this is only generated once and I have a SPA.

This works of course:

beforeFilter: $this->getEventManager()->off($this->Security);

来源:https://stackoverflow.com/questions/54562777/cakephp-3-7-3-use-securitycomponent-with-ajax-with-spa

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