authentication redirect valve Jahia 7.3 Jahia 8

How to avoid IllegalStateException in URL redirections from authentication valve?


I implemented a custom authentication valve which performs a redirection before invoking the next valve in the pipeline.

The authentication works fine, but every time the redirection is performed I observe the following exception in Jahia logs:

2021-04-26 15:43:02,859: ERROR [ErrorPageHandler] - java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

Is there a way to avoid this exception?


The easiest way to avoid this exception after performing the redirection is to explicitly throw JahiaUnauthorizedException instead of invoking the next valve in the pipeline. This way, we can ensure no other valves will be executed.

Taking this example, if we had a redirection instruction like this at the end of the valve execution: 


We can simply throw the exception right after the redirection to ensure that the IllegalStateException exception is not thrown anymore:

throw new JahiaUnauthorizedException();

Now the Error is gone and the redirection still works as expected.