博客 / 詳情

返回

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

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.