PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, March 13, 2022

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

 March 13, 2022     ajax, cakephp, csrf, csrf-token, php     No comments   

Issue

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 :

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.

So my AJAX request cannot be sent if visitor just arrived on my website without visiting other pages before.

I know that in cakePHP 3.X the csrfToken was stocked in session directly. Do you have a solution for my problem ?

Thank you for your help

Best regards,

Loic


Solution

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.

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:

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

See also

  • Cookbook > Middleware > CSRF Middleware > CSRF Protection and AJAX Requests


Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing