Create a filter class for enabling CORS
CORS ( Cross-Origin Resource Sharing ) is a mechanism provided by modern web browser to allow cross-site HTTP requests like XmlHttpRequest (Ex. Ajax).
This article does not cover discussions and articles about the CORS standard, – for which we refer to Wikipedia or MSDN article – instead we’ll show an example in Java on how dinamically enable CORS and send back the information to the client browser.

According the above scenario, our CORS filter must intercept the Origin value contained on the HEAD part of the request sent by the client.
Configure allowed site or domains
On the web application’s properties file, add a dedicated key where insert thrusted domain.
Something like this:
cors.domain.supported = *.mythrusteddomain.it
Then consider writing a class that implements a javax.servlet.Filter.
@WebFilter(urlPatterns="/*") public class ApiOriginFilter implements Filter { @Inject ConfigService config; @Inject Logger logger; static String origins; static Pattern pattern; @Override public void init(FilterConfig filterConfig) throws ServletException { origins = config.getProperty("cors.domain.supported"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (StringUtils.isNotEmpty(origins)) { String[] list = origins.split(","); HttpServletRequest httpServletRequest = (HttpServletRequest)request; String origin = httpServletRequest.getHeader("Origin"); logger.debug("origin: {}", origin); if (StringUtils.isNotEmpty(origin)) { for (String item : list) { String input = item.trim(); String regex = "^" input.replace("*", ".*") "(?::d )$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(origin); if (matcher.find()) { String output = matcher.group(0); logger.info("origin allowed: {}", output); HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.addHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization"); } } } } chain.doFilter(request, response); } @Override public void destroy() { }
Notice that if you are developting with REST API and JAX-RS 2.0, a better choice would be to implement ContainerResponseFilter class instead.
Test on local environment
In order to test ajax call on the same local environment, a simple way is to edit OS host’s file by adding a line:
127.0.0.1 foo.yourdomain.it
Then every XHRequest will point to http://foo.yourdomain.it
/[service_address].
Leave a Reply