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:

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

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].

1 Comment

  1. I wonder, is it okay to return Access-Control-Allow-Origin: * header (with the wildcard)? Will it be more secure to return this header with the Origin value if this origin is allowed of course?

Leave a Reply

Your email address will not be published.

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