CORS – How to allow origin by domain using wildcard operator

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.

an XmlHttpRequest request

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 = *

Then consider writing a class that implements a javax.servlet.Filter.

public class ApiOriginFilter implements Filter {

	ConfigService config;
	Logger logger;
	static String origins;
	static Pattern pattern;
	public void init(FilterConfig filterConfig) throws ServletException {
		origins = config.getProperty("cors.domain.supported");
	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 =;
			"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);


	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:

Then every XHRequest will point to[service_address].

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see