Using CORS Headers with Java (example)

Using CORS with Java

Download CORS example directly from Dropbox or find it here on Github 

We can implement Cross Origin Resource Sharing (CORS) in Java in multiple ways. There’s a number of packages available, for example the Tomcat Catalina CORS filter. At the beginning Catalina gave me a couple of problems so I ended up making a custom filter, but I also included how to include the Catalina CORS filter. The main idea to remember when writing your own filter is that, before any AJAX calls are made. The browser sends an OPTIONS AJAX request to the server. The server needs to reply to this OPTIONS call with the required permissions.

The custom CORS filter needs to react whenever it received an OPTIONS AJAX call from the client. At this point the browser should have the required information, however atleast in my case not adding CORS headers to subsequent responses would cause them to fail with CORS violations. So they are just added to all calls. The code is a great starting point for implementing CORS without security.

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    System.out.println("Request: " + request.getMethod());

    HttpServletResponse resp = (HttpServletResponse) servletResponse;
    resp.addHeader("Access-Control-Allow-Origin","*");
    resp.addHeader("Access-Control-Allow-Methods","GET,POST");
    resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");

    // Just ACCEPT and REPLY OK if OPTIONS
    if ( request.getMethod().equals("OPTIONS") ) {
        resp.setStatus(HttpServletResponse.SC_OK);
        return;
    }
    chain.doFilter(request, servletResponse);
}

 @Override
public void destroy() {}
}

To web.xml just add

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>CORSFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>*</url-pattern>
</filter-mapping>

Catalina CORS Filter

Catalina CORS Filter Documentation

After a little playing around I was able to successfully implement the Catalina CORS filter.

<dependency>
   <groupId>org.apache.tomcat</groupId>
   <artifactId>tomcat-catalina</artifactId>
   <version>8.0.5</version>
</dependency>

and include the provided Tomcat CORS filter with web.xml

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
    </init-param>
    <init-param>
       <param-name>cors.exposed.headers</param-name>
       <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
    <init-param>
        <param-name>cors.support.credentials</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>cors.preflight.maxage</param-name>
        <param-value>10</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s