javascript - A very basic approach to the double submit cookie patterns for ajax requests in (partly) stateless web applications

My self-coded very basic approach to implement the double submit cookie pattern (detailed information: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie) in a partly stateless web application without framework written in PHP and JavaScript (jQuery) would be like this:

PHP - for each request:

setcookie(
    "meow_csrf",
    $value = "some_securly_generated_random_string",
    0,
    "/",
    "mydomain.com",
    true,
    false
);

JavaScript - for ajax requests:

// JS
$.ajax({
    type: "POST",
    url: '/ajax.php?action=update_user_details&meow_csrf=' . $.cookie('meow_csrf'),
    error: function() {
        // blabla
    },
    success: function(data){
        // blabla
    }
});

PHP - server side check:

function tokenCheck(): bool 
{
    return $_COOKIE["meow_csrf"]) === urldecode($_GET["meow_csrf"]);
}

Please note how setcookie in PHP works: https://www.php.net/manual/en/function.setcookie.php

Is this already a basic protection against CSRF attacks or did I misunderstand something? Please note that the cookie may only be transferred via HTTPS, it can therefore not be easily read over a network. It is not HTTPOnly though.

Answer

Solution:

Note that there could be some problems when you renew the cookie for EVERY request. Let's say a user fills out a form and opens another tab in the meantime (maybe to look something up). When he finally sends the form the cookie already changed due to the requests in the meantime. This will also happen with any call in general between first initializing the page and finally send the request.

I think once the CRSF Token is set you don't need to change it for the current session. And yes, I would call that a basic approach against CRSF attacks.

Source