Make simple servlet filter work with @ControllerAdvice

后端 未结 3 1956
野性不改
野性不改 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:31

    You can't use @ControllerAdvice, because it gets called in case of an exception in some controller, but your ClientKeyFilter is not a @Controller.

    You should replace the @Controller annotation with the @Component and just set response body and status like this:

    @Component
    public class ClientKeyFilter implements Filter {
    
        @Value('${CLIENT_KEY}')
        String clientKey
    
        public void init(FilterConfig filterConfig) {
        }
    
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
    
            String reqClientKey = request.getHeader("Client-Key");
    
            if (!clientKey.equals(reqClientKey)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid API key");
                return;
            }
    
            chain.doFilter(req, res);
        }
    
        public void destroy() {
        }
    }
    

提交回复
热议问题