Content Security Policy (CSP)
Examples


CSP Java Example

Here's how to add a Content-Security-Policy HTTP response header using Java.

Example CSP Header with Java

By referencing the HTTP Servlet API, we can use the addHeader method of the HttpServletResponse object.

response.addHeader("Content-Security-Policy", "default-src 'self'");

Your policy will go inside the second argument of the addHeader method in the example above.

Using your Web Server

Instead of writing the header directly from your Java code or JSP code, you can instead use your web server to write the header. For example CSP with nginx or CSP with Apache via htaccess.

Writing a HTTP Servlet Filter

If you want to apply the same policy to all requests to your java application server you can create a simple HTTP Servlet Filter. It is usually easier to use the web server, if you have one, but if you are serving requests directly from Apache Tomcat, or another J2EE server a Servlet Filter may be a good way to go.

Here is an example java servlet filter to add a CSP response header:

package com.content-security-policy.filters;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletResponse

import java.io.IOException;

public class CSPFilter implements Filter {
	
	public static final String POLICY = "default-src 'self'";

	@Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
        
    if (response instanceof HttpServletResponse) {
      ((HttpServletResponse)response).setHeader("Content-Security-Policy", CSPFilter.POLICY);
    }
    chain.doFilter(request, response);
  }
    
	@Override
  public void init(FilterConfig filterConfig) throws ServletException { }

	@Override
  public void destroy() { }

}

Then enable the java servlet filter in your web.xml:

<filter>
  <filter-name>CSPFilter</filter-name>
  <filter-class>com.content-security-policy.filters.CSPFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CSPFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

What goes inside a CSP policy?

If you're not sure what default-src 'self'; means, then check out the Content Security Policy reference for details. That is just a really simple example of a policy, your policy will probably need to be more complex than that.

CSP Developer Field Guide

CSP Developer Field Guide

Want to learn the ins and outs CSP? Grab a copy of the CSP Developer Field Guide. It's a short and sweet guide to help developers get up to speed quickly.

Grab a Copy

Struggling to stay on top of security advisories?

Advisory Week is a weekly roundup of all the security advisories published by the major software vendors.