We are currently working on adding headers for each response from our application. To add these headers, we use the Servlet Filter -interface APIs.
We have the following filter in our application:
public class SecurityFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); HttpServletResponse httpServletResponse = ((HttpServletResponse) response); httpServletResponse.addHeader("X-Frame-Options", "DENY"); httpServletResponse.addHeader("X-Content-Type-Options", "nosniff"); } @Override public void destroy() { } }
This (in particular, the doFilter method) is executed correctly in accordance with the documentation, which assumes the following procedure:
As far as we can see, the order of our doFilter method is correct in accordance with the documentation (first pass the request to the chain as indicated in paragraph 4, then add custom headers as indicated in paragraph 5). However, the headers we add do not appear in the responses. If we change the order to the following, everything will work fine:
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpServletResponse = ((HttpServletResponse) response); httpServletResponse.addHeader("X-Frame-Options", "DENY"); httpServletResponse.addHeader("X-Content-Type-Options", "nosniff"); chain.doFilter(request, response); }
Can anyone explain this behavior?
source share