There are two ways you can enable CORS for a Liberty server:
- Use a JAX-RS response filter (if the endpoints are JAX-RS resources)
- Use the
<cors>
configuration element in server.xml
To use the JAX-RS response filter way:
Add this class to your JAX-RS application:
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
responseContext.getHeaders().add("Access-Control-Max-Age", "1209600");
}
}
To use the server.xml way:
Add the following configuration element to your server.xml:
<!-- May need to adjust the 'domain' depending on
what elements you want to enable CORS for -->
<cors domain="/"
allowedOrigins="*"
allowedMethods="GET, DELETE, POST, PUT"
allowedHeaders="origin, content-type, accept, authorization, cache-control"
maxAge="3600" />
If you are using the server.xml way with Docker, if you aren't doing so already, you need to add the server.xml configuration into your Docker image like this:
FROM open-liberty:microProfile2
ADD --chown=1001:0 build/libs/myApp.war /config/dropins
# Assuming the server.xml is in the src/main/liberty/config/ folder
COPY --chown=1001:0 src/main/liberty/config /config/