概述
Spring Security 提供了 RequestRejectedHandler 來處理當請求被拒絕時候如何處理,在沒有進行配置的情況下,默認是使用 DefaultRequestRejectedHandler 直接將異常進行拋出:
throw requestRejectedException;
同時也提供了 HttpStatusRequestRejectedHandler 來返回對應的狀態碼。
定製 RequestRejectedHandler
RequestRejectedHandler 的注入是在 WebSecurity 的 setApplicationContext 當中:
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