在SpringBoot版本2.1.6中无法拦截访问执行器请求
现在我有一个全局拦截器
@Component
public class ServiceFilter implements HandlerInterceptor {
//log4j
static final Logger logger = LogManager.getLogger(ServiceFilter.class);
private final RateLimiter limiter = RateLimiter.create(Runtime.getRuntime().availableProcessors() * 2 + 1);
private final ThreadLocal<ExecuteRecordDto> executeRecord = new ThreadLocal<>();
public ServiceFilter() {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ExecuteRecordDto recordDto = ExecuteRecordDto.bulider(request);
executeRecord.set(recordDto);
if (!limiter.tryAcquire()) {
logger.warn("rate limiter ; json logger : {}",CommonUtil.toJSONString(recordDto));
response.getWriter().print(CommonUtil.toJSONString(ResultStatus.status(407, "rate limiter")));
return false;
}
if (ObjectUtils.isEmpty(request.getHeader("Authorization"))) {
logger.warn("illegal request, json logger : {} ",CommonUtil.toJSONString(recordDto));
response.getWriter().print(CommonUtil.toJSONString(ResultStatus.status(403, "Permission denied")));
return false;
}
switch (TokenHandle.checkToken(request.getHeader("Authorization"))) {
//正常放行token
case 0:
response.getWriter().print(CommonUtil.toJSONString(ResultStatus.status(407, "rate limiter")));
return true;
//token 过期
case 1:
response.getWriter().println(CommonUtil.toJSONString(ResultStatus.status(408, "Token expire")));
break;
//非法token
case 2:
logger.warn("illegal token, json logger : {} ",CommonUtil.toJSONString(recordDto));
response.getWriter().print(CommonUtil.toJSONString(ResultStatus.status(409, "Illegal token ")));
break;
default:
throw new RuntimeException("server runtime exception");
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
ExecuteRecordDto recordDto = executeRecord.get();
logger.info("json logger : {}",CommonUtil.toJSONString(recordDto));
executeRecord.remove();
}
}
并使其工作
@Configuration
public class ConfigFilter implements WebMvcConfigurer {
private final ServiceFilter filter;
@Autowired
public ConfigFilter(ServiceFilter filter){
this.filter = filter;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(filter).addPathPatterns("/**");
}
}
我请求了自己的api,获得了我想要的效果
SpringBoot如何拦截执行器的访问
最佳答案
执行器正在使用其他HandlerMapping(请参阅:org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping
)。
由于顺序(-100 vs 0),将在您配置的RequestHandlerMapping上选择此Handlermapping。您可以在DispatcherServlet
方法HandlerExecutionChain getHandler(HttpServletRequest request)
中看到它。
在我们的项目中,我们使用弹簧安全性配置对执行器端点的访问,因此我不知道是否有建议的方法,但是:
处理程序是按顺序选择的,因此要考虑这一点,您也可以尝试操纵执行器WebMvcEndpointHandlerMapping
。
就像我说的那样,我不确定正确的解决方案,但是我希望它为您找到正确的解决方案指明了正确的方向。
问候,WiPu