How customize 403 and 500 error messages

Hello,

I’m using Spring Boot and Keycloak and I want to customize the 404 - Not found error page and the 500 - Internal Server Error.

I have overwritten KeycloakWebSecurityConfigurerAdapter and the method keycloakAuthenticationProcessingFilter to setup a custom AuthenticationFailureHandler.

    @Bean
    @Override
    protected KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {

        KeycloakAuthenticationProcessingFilter filter =
                new McdKeycloakAuthenticationProcessingFilter(authenticationManagerBean(), requestMatcher);

        filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
        filter.setAuthenticationFailureHandler(this.mcdKeycloakAuthenticationFailureHandler);
        filter.setAuthenticationSuccessHandler(this.mcdAuthenticationSuccessHandler);
        return filter;
    }

And my AuthenticationFailureHandler looks like

@Component
public class McdKeycloakAuthenticationFailureHandler extends KeycloakAuthenticationFailureHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(McdKeycloakAuthenticationFailureHandler.class);

    @Autowired
    DefaultErrorHandler defaultErrorHandler;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        LOGGER.debug("onAuthenticationFailure {}",  exception.toString());

        // Check that the response was not committed yet (this may happen when another
        // part of the Keycloak adapter sends a challenge or a redirect).
        if (!response.isCommitted()) {
            if (KeycloakCookieBasedRedirect.getRedirectUrlFromCookie(request) != null) {
                response.addCookie(KeycloakCookieBasedRedirect.createCookieFromRedirectUrl(null));
            }

            defaultErrorHandler.handleCommonException(HttpStatus.UNAUTHORIZED, exception);
        } else {
            LOGGER.debug("onAuthenticationFailure - response isCommitted - Status: {}",  response.getStatus());
            if (200 <= response.getStatus() && response.getStatus() < 300) {
                throw new RuntimeException("Success response was committed while authentication failed!", exception);
            }
        }
    }
}

However, I’m not able to set a custom response for 404/500 since the response is already committed at this point.

Do you know how to return a custom error page/response for these errors ?