Make simple servlet filter work with @ControllerAdvice

后端 未结 3 1977
野性不改
野性不改 2021-01-04 05:32

I\'ve a simple filter just to check if a request contains a special header with static key - no user auth - just to protect endpoints. The idea is to throw an AccessFo

3条回答
  •  自闭症患者
    2021-01-04 06:19

    As specified by the java servlet specification Filters execute always before a Servlet is invoked. Now a @ControllerAdvice is only useful for controller which are executed inside the DispatcherServlet. So using a Filter and expecting a @ControllerAdvice or in this case the @ExceptionHandler, to be invoked isn't going to happen.

    You need to either put the same logic in the filter (for writing a JSON response) or instead of a filter use a HandlerInterceptor which does this check. The easiest way is to extend the HandlerInterceptorAdapter and just override and implement the preHandle method and put the logic from the filter into that method.

    public class ClientKeyInterceptor extends HandlerInterceptorAdapter {
    
        @Value('${CLIENT_KEY}')
        String clientKey
    
        @Override
        public boolean preHandle(ServletRequest req, ServletResponse res, Object handler) {
            String reqClientKey = req.getHeader('Client-Key')
            if (!clientKey.equals(reqClientKey)) {
              throw new AccessForbiddenException('Invalid API key')
            }
            return true;
        }
    
    }
    

提交回复
热议问题