Adding CORS headers to your Java-based REST server responses is more tricky than it needs to be. There seems to be an oversight in Java EE’s filter handling, because when the container is configured with container managed authorization and a user that is not (yet) authenticated attempts to access a protected resource, the container intercepts that request and sends a 401 response. That response does not have CORS headers, but for some reason cannot be filtered. Neither with a Jax-Rs ContainerResponseFilter, not with a plain servlet filter. A container-specific solution seems to be the only way to get the job done.
I created an Undertow filter to get this job done easily for JBoss Undertow based EE servers. These include JBoss AS/EAP, Wildfly and Wildfly Swarm. The Github project, which includes installation instructions, can be found here:
I am currently in the process of publishing this project to Maven Central. Update will follow soon!