简体   繁体   English

CakePHP 4 csrfToken cookie 未在第一页加载时设置

[英]CakePHP 4 csrfToken cookie not set on the first page load

I am using cakePHP 4.2.3 On my home page I have a form and I want to submit this one with ajax, with cakePHP, we have to specify in the header of AJAX request the "X-CSRF-Token" and to get this one, I have to do this: I am using cakePHP 4.2.3 On my home page I have a form and I want to submit this one with ajax, with cakePHP, we have to specify in the header of AJAX request the "X-CSRF-Token" and to get this一,我必须这样做:

var csrfToken = <?= json_encode($this->request->getCookie('csrfToken')) ?>;

This work very fine, but on the first page load, I can't access to csrfToken cookie,I have to refresh the page again to access to the cookie.这项工作非常好,但是在第一个页面加载时,我无法访问 csrfToken cookie,我必须再次刷新页面才能访问 cookie。

So my AJAX request cannot be sent if visitor just arrived on my website without visiting other pages before.因此,如果访问者刚刚到达我的网站而之前没有访问其他页面,则无法发送我的 AJAX 请求。

I know that in cakePHP 3.X the csrfToken was stocked in session directly.我知道在 cakePHP 3.X 中,csrfToken 直接存放在 session 中。 Do you have a solution for my problem?你有解决我的问题的方法吗?

Thank you for your help谢谢您的帮助

Best regards,此致,

Loic洛伊克

If at all, you would read the value from the response cookie, that is the cookie that is being set by your application, not from the request cookie, which is the cookie sent to your application by the user.如果有的话,您将从响应cookie 中读取值,即由您的应用程序设置的 cookie,而不是从请求cookie 中读取值,后者是用户发送给您的应用程序的 cookie。

However in your application you better stay agnostic, and do it as shown in the docs, read the token from the csrfToken request attribute that is being set by your application:但是,在您的应用程序中,您最好保持不可知论,并按照文档中所示进行操作,从您的应用程序设置的csrfToken请求属性中读取令牌:

$this->request->getAttribute('csrfToken')

See also也可以看看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM