需求描述:需要根据用户的请求路径拦截做权限控制:
但是这样做全局异常无法捕获
解决方案:
在filter当中引入HandlerExceptionResolver类,通过该类的resolveException方法抛出自定义异常:
- public class OpenInvokeFilter extends OncePerRequestFilter {
-
- @Autowired
- private GaioAuthorizedProperties gaioAuthorizedProperties;
-
- @Autowired
- @Qualifier("handlerExceptionResolver")
- private HandlerExceptionResolver resolver;
-
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
- throws ServletException, IOException {
- boolean containsUri = request.getRequestURI().contains("/open/invoke");
- if (containsUri) {
- String paasid = request.getHeader("x-tif-paasid");
- String serviceId = request.getHeader("x-smp-serviceid");
- if (StringUtils.isNotBlank(paasid)) {
- // 从yml获取匹配数据,判断当前paasId是否有权限调用指定的serviceId,无权限则拦截处理。
- AccessProperties accessProperties = gaioAuthorizedProperties.getType().get("ebus");
- Map
passServiceMap = accessProperties.getPassServiceMap(); - String[] serviceIds = passServiceMap.get(paasid);
- if (serviceIds == null) {
- resolver.resolveException(request, response,
- null, new GaioBizException(RESOURCE_NOT_FOUND_ERROR));
- return;
- }
- boolean match = Arrays.stream(serviceIds).anyMatch(item -> item.equals(serviceId));
- if (!match) {
- resolver.resolveException(request, response,
- null, new GaioBizException(RESOURCE_NOT_FOUND_ERROR));
- return;
- }
- }
- }
- chain.doFilter(request, response);
- }
-
- }