Issue
I use keycloak-spring-boot-starter
to protect my rest-service from unauthorized access.
The authentication works as expected, but if the authentication fails, then it returns an empty response.
However, I'd like to return a json error response similar to all my other error handlers.
I already tried to define an @ExceptionHandler(Throwable.class)
, ErrorController
, ErrorViewResolver
or configuring the ErrorPage
s via WebServerCustomizer
, but that doesn't work at all.
I'm totally fine, if I could define a static response for it.
There seems to be a property called delegateBearerErrorResponseSending
, but I couldn't find where to set it. It isn't present in spring-boot's properties. I'm not even sure where the call will be delegated to.
There is a property called policy-enforcer-config.on-deny-redirect-to
, but a redirect isn't the expected behavior for a rest service.
- spring-boot: 2.3.1.RELEASE
- keycloak-spring-boot-starter: 10.0.2
TLDR: How do I configure/customize the error page for keycloak.
Solution
I found a way to do this to a certain degree in current spring-security-web (5.4+) versions.
/**
* A {@link RequestRejectedHandler} for spring security web's application firewall.
*/
@Component
public class FirewallRequestRejectedHandler implements RequestRejectedHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(FirewallRequestRejectedHandler.class);
@Override
public void handle(
final HttpServletRequest request,
final HttpServletResponse response,
final RequestRejectedException requestRejectedException) throws IOException {
// Optionally write a warning to the logs
LOGGER.warn("Application firewall: {}", requestRejectedException.getMessage(),
LOGGER.isDebugEnabled() ? requestRejectedException : null);
// Make the exception accessible to the ErrorController
request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, requestRejectedException );
// Call error controller
response.sendError(401, "Access denied");
}
}
This will call the ErrorController
which contains my fallback error handling logic, which results in the correct response being sent.
Answered By - ST-DDT