Return HTTP Error 401 Code & Skip Filter Chains

I suggest this solution below.

public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        final String val = request.getHeader(FOO_TOKEN)

        if (val == null || !val.equals("FOO")) {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "The token is not valid.");
        } else {
            chain.doFilter(req, res);
        }
    }

From the API docs for the doFilter method, you can:

  • Either invoke the next entity in the chain using the FilterChain object (chain.doFilter()),
  • or not pass on the request/response pair to the next entity in the filter chain to block the request processing

so setting the response status code and returning immediately without invoking chain.doFilter is the best option for what you want to achieve here.