How customize 403 and 500 error messages


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.

    protected KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {

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

        return filter;

And my AuthenticationFailureHandler looks like

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

    DefaultErrorHandler defaultErrorHandler;

    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) {

            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 ?