我使用 keycloak-spring-boot-starter
来保护我的休息服务免受未经授权的访问。
身份验证按预期工作,但如果身份验证失败,则会返回空响应。
但是,我想返回一个类似于我所有其他错误处理程序的 json 错误响应。
我已经尝试定义一个 @ExceptionHandler(Throwable.class)
、ErrorController
、ErrorViewResolver
或配置 ErrorPage
通过 WebServerCustomizer
,但这根本不起作用。
我完全没问题,如果我能为它定义一个静态响应的话。
似乎有一个名为 delegateBearerErrorResponseSending
的属性,但我找不到在哪里设置它。它不存在于 spring-boot 的属性中。我什至不确定电话会被委托(delegate)到哪里。
有一个名为 policy-enforcer-config.on-deny-redirect-to
的属性,但重定向不是休息服务的预期行为。
- spring-boot: 2.3.1.RELEASE
- keycloak-spring-boot-starter: 10.0.2
TLDR:如何配置/自定义 keycloak 的错误页面。
最佳答案
我在当前的 spring-security-web (5.4+) 版本中找到了一种在一定程度上做到这一点的方法。
/**
* 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");
}
}
这将调用包含我的回退错误处理逻辑的 ErrorController
,这会导致发送正确的响应。
关于java - 使用 spring boot 自定义 keycloak 错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62916394/