Spring Security – RequestRejectedException

概述

Spring Security 提供了 RequestRejectedHandler 来处理当请求被拒绝时候如何处理,在没有进行配置的情况下,默认是使用 DefaultRequestRejectedHandler 直接将异常进行抛出:

throw requestRejectedException;

同时也提供了 HttpStatusRequestRejectedHandler 来返回对应的状态码。

定制 RequestRejectedHandler

RequestRejectedHandler 的注入是在 WebSecuritysetApplicationContext 当中:

try {
    this.requestRejectedHandler = applicationContext.getBean(RequestRejectedHandler.class);
}
catch (NoSuchBeanDefinitionException ex) {
}
if (this.requestRejectedHandler != null) {
   filterChainProxy.setRequestRejectedHandler(this.requestRejectedHandler);
}

在中的定义为:

private RequestRejectedHandler requestRejectedHandler = new DefaultRequestRejectedHandler();

我们只需要覆盖 Bean 定义即可:

@Bean
RequestRejectedHandler requestRejectedHandler() {
   return new CustomizerRequestRejectedHandler();
}
@Slf4j
public class CustomizerRequestRejectedHandler implements RequestRejectedHandler {
   @Override
   public void handle(HttpServletRequest request, HttpServletResponse response,
   RequestRejectedException ex) throws IOException, ServletException {
      log.warn("request uri: {},user-agent: {}", request.getRequestURI(), request.getHeader(HttpHeaders.USER_AGENT));
      log.error(ex.getMessage(), ex);
      response.setStatus(HttpServletResponse.SC_NOT_FOUND);
   }
}

参考

spring-5-0-3-requestrejectedexception-the-request-was-rejected-because-the-url

log+request+uri+on+RequestRejectedException

how-to-intercept-a-requestrejectedexception-in-spring

spring-security-request-rejected-exception

posted @   codeshaw  阅读(215)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示