Can Tomcat 7 be configured to insert "Content-Security-Policy" HTTP header?

19,506

Once it cannot be achieved with Tomcat 7.x built in filters, you could try one of the following options:

Creating a filter in your application

If adding a filter to your application is an option, you could use the following code to add a header to every response:

@WebFilter("/*")
public class MyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, 
                         FilterChain chain) throws IOException, ServletException {

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Content-Security-Policy", "frame-ancestors 'self'");

        chain.doFilter(request, response);
    }
}

Creating a custom valve in your Tomcat

Another option is a custom valve. Quoting the steps from this page:

  1. Create a Maven Java Application.

  2. Add the following dependency:

<dependency>
    <groupid>org.apache.tomcat</groupId>
    <artifactid>tomcat-catalina</artifactId>
    <version>7.0.34</version>
    <scope>provided</scope>
 </dependency>
  1. Create your Java class and extend it from ValveBase.

  2. Implement the invoke(Request, Response) method.

  3. Build your library (.jar) file

  4. Install the library in the ${tomcat.home}/lib directory.

  5. Configure the server.xml to use your new valve. For example:

<valve className="com.example.MyValve"/>
  1. Start the server to see your new valve in action

Your valve implementation could be like:

public class MyValve extends ValveBase {

    @Override
    public void invoke(Request request, Response response) throws IOException, 
                                                                  ServletException {

        HttpServletResponse httpResponse = response.getResponse();
        httpResponse.setHeader("Content-Security-Policy", "frame-ancestors 'self'");

        getNext().invoke(request, response);
    }
}
Share:
19,506

Related videos on Youtube

Peter Klimczak
Author by

Peter Klimczak

Updated on June 04, 2022

Comments

  • Peter Klimczak
    Peter Klimczak almost 2 years

    Can Tomcat 7 be configured to insert Content-Security-Policy: frame-ancestors 'self' HTTP header with every response, like it can insert other security related headers, for example X-Frame-Options?

  • Peter Klimczak
    Peter Klimczak almost 8 years
    Thank you for the answer. I should have mentioned "without code change".
  • cassiomolin
    cassiomolin almost 8 years
    @PeterKlimczak I think a custom valve can do the trick. I'll update my answer.