Customization of the 401 error message in the Keycloak authentication call response

Hello there! I’m having trouble regarding the handling and customization of exceptions in Keycloak - specifically customizing the message for error 401.

Like, when the isValid method gets a return false, I need to get the information about de authentication status response error and inform(or throw) in the response of the HTTP request. For exemple, I want to change the erro_description, as you can see in the postman print bellow :

To something like this:

  • {
    error: invalid_grant,
    error_description: “information that came from the other api that authenticate and confirm the isValid”
    } -

I’m using the 18.0.0. version of Keycloak-SPI, Spring Boot 3 and Java 17.

Thank you so much!

Mostrar menos

1 Like

Hi guys! @davidv, is right. The thing is, the WebApplicationException (javax version for Spring 3) has to receive a Throwable in the constructor; otherwise, it’s going to respond with a 500 error. At least in the version that I’m using for keycloak(18.0.0) and spring boot(3.0). Example:

try {
    // ... code
} catch (WebApplicationException ex) {
    log.error("Authentication Error", ex);
    Throwable throwable = new Throwable(ex.getMessage());
    throw new WebApplicationException(ex.getMessage(), throwable, ex.getResponse());
}

Also, it’s important to know that the same 500 error occurs when the Response parameter is null . Yeap, were just a simple documentation and basics about exceptions! kkkk
Thank you, everyone.