Welcome Guest, Not a member yet? Register   Sign In
How to handle SecurityException #403 globally?
#1

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?
Reply
#2

Look at the MagicLinkController
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

This exception is already thrown inside a try-catch block in the before method of the CSRF filter (https://github.com/codeigniter4/CodeIgni...s/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/libra...urity.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.

CodeIgniter Wizard (CRUD code generator for Mac) instantly scaffolds Bootstrap-based web applications with an administrative interface (admin templates include Bootstrap5)

Reply




Theme © iAndrew 2016 - Forum software by © MyBB