CodeIgniter Forums
How to handle SecurityException #403 globally? - 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: How to handle SecurityException #403 globally? (/showthread.php?tid=91876)



How to handle SecurityException #403 globally? - fcoder - 10-28-2024

Hello folks,
When I restored browser pages from the last session, I noticed my CI4 app throwing "CodeIgniter\Security\Exceptions\SecurityException #403 The action you requested is not allowed." taking place at the urlĀ 'localhost:8080/login/magic-link'. I know this occurs when a csrf token expired, but I'm looking for a nicer way to output to the browser like showing a flash message or redirecting the user to the last form they were on.
How and where can one capture this in a try catch block to begin with?


RE: How to handle SecurityException #403 globally? - InsiteFX - 10-28-2024

Look at the MagicLinkController


RE: How to handle SecurityException #403 globally? - gosocial2 - 10-29-2024

This exception is already thrown inside a try-catch block in the before method of the CSRF filter (https://github.com/codeigniter4/CodeIgniter4/blob/develop/system/Filters/CSRF.php), but it is only thrown when CI_ENVIRONMENT != production.

In production, the user would be redirected to the previous page as per the below paragraph in the docs (at https://codeigniter.com/user_guide/libraries/security.html):

Redirection on Failure
Starting with v4.5.0, when a request fails the CSRF validation check, by default, the user is redirected to the previous page in production environment, or a SecurityException is thrown in other environments.

Therefore, if your end goal is prevent an exception to be thrown and avoid possible log noise, etc, you can configure public bool $redirect = true in app/Config/Security.php (it is public bool $redirect = (ENVIRONMENT === 'production') by default.

Otherwise, if you'd rather going deep down to a lower level dealing with the exception, you can override the CSRF.class and do your customization in the before method.