How to catch "CSRF token from either the request body or request headers did not match or is missing."

When a login window is opened for a long time, then the exception Cake\Http\Exception\InvalidCsrfTokenException with the additional text “CSRF token from either the request body or request headers did not match or is missing.” is thrown.

Looking at the stack I thought I can fix it with this small code in webroot/index.php

try {

    $server->emit($server->run());

} catch ( \Cake\Http\Exception\InvalidCsrfTokenException ) {

    foreach ( array_keys($_COOKIE) as $cookieKey ) {

        setcookie( $cookieKey, FALSE );

    }

    header("Location: https://example.com/users/login");
    exit;

}

But I was wrong. The exception is still thrown. Where should I place this code, or, how can I fix it so the user never sees this error message and the site brings itself into a stable state?

Using CakePHP 4.4.14

Just disable the CSRF middleware?

Strange point of view. I should disable something I want to use just because the framework doesn’t offer a catch possibility?

I was naive to think that a personalised catch solves it.

Sorry, when you said you never wanted the user to see it, I thought that meant you didn’t care if the feature was used.

So, this means, CakePHP doesn’t offer any possibility to catch this exception, so the user doesn’t see this - or any similar - error messages? Really? I don’t believe it.

You can build your own WebExceptionRenderer
https://book.cakephp.org/4/en/development/errors.html

1 Like

Thank you very much Kevin!

This was exactly what I was looking for. Now the page reloads itself when this exception is thrown!

By the way, the documentation to which you refer should be updated as the example uses use Cake\Error\ExceptionRenderer; but according to the PhpStorm warning and the comment in the CakePHP source code it seems to be deprecated.

Maybe somebody finds time to update it.

* @deprecated 4.4.0 Use Cake\Error\Renderer\WebExceptionRenderer instead.