CodeIgniter Forums
Custom error message for Csrf validation - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Custom error message for Csrf validation (/showthread.php?tid=88843)



Custom error message for Csrf validation - semprom - 11-18-2023

Hi,
how can we have custom error message displayed when the CSRF validation fails instead of the exception thrown usually?
Thanks.


RE: Custom error message for Csrf validation - kenjis - 11-18-2023

See https://codeigniter4.github.io/CodeIgniter4/libraries/security.html#redirection-on-failure


RE: Custom error message for Csrf validation - semprom - 11-19-2023

(11-18-2023, 06:58 PM)kenjis Wrote: See https://codeigniter4.github.io/CodeIgniter4/libraries/security.html#redirection-on-failure

I don't want to redirect back. I just want to display a simple message when the csrf request has failed.


RE: Custom error message for Csrf validation - kenjis - 11-19-2023

Try/catch the SecurityException and show an error message you want.


RE: Custom error message for Csrf validation - semprom - 11-24-2023

(11-19-2023, 12:59 AM)kenjis Wrote: Try/catch the SecurityException and show an error message you want.

For some reason I cannot catch the exception. I tried with the bellows but without result.

try {

...

} catch (SecurityException $e) { / } catch (\SecurityException $e) {


}


RE: Custom error message for Csrf validation - kenjis - 11-24-2023

Check the CI4 source code. The classname is \CodeIgniter\Security\Exceptions\SecurityException.


RE: Custom error message for Csrf validation - semprom - 11-24-2023

(11-24-2023, 05:49 PM)kenjis Wrote: Check the CI4 source code. The classname is \CodeIgniter\Security\Exceptions\SecurityException.

I tried also that, it didn't work.


RE: Custom error message for Csrf validation - kenjis - 11-24-2023

If you try to catch the exception in your controller, sorry you can't.
Because CSRF filter throws the exception. The controller is not executed yet.

Customize CSRF filter.