I have a general idea about how it works. I return the same "ORIGIN" value if the the request's "origin" header is valid (allowed)
But I don't know:
- For the actual request following the OPTIONS request, do I need to include the exact same Access-Control-Allow-Origin header that I returned to the client for the preflight request? Should the server code only need to do this when there is an "ORIGIN" header present in the actual request? (in the code below, I did not check whether the request is a OPTIONS/preflight request or the actual one, I assume the same code can apply to both with no harm).
(More details, because "The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'," so I need the ORIGIN value from the request to put back into the response.
What should I return if the ORIGIN is not allowed?
not including the Access-Control-Allow-Origin header at all?
or setHeader("Access-Control-Allow-Origin", ""), or setHeader("Access-Control-Allow-Origin", "null")?
public class CORSResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
MultivaluedMap<String, Object> headers = responseContext.getHeaders();
String origin = requestContext.getHeaderString("Origin");
String origin = requestContext.getHeaderString("Origin");
URL originUrl = null;
try {
if (StringUtils.hasText(origin)) {
originUrl = new URL(origin);
Pattern hostAllowedPattern = Pattern.compile("(.+\\.)*mydomain\\.com", Pattern.CASE_INSENSITIVE);
if (hostAllowedPattern.matcher(originUrl.getHost()).matches()) {
headers.add("Access-Control-Allow-Origin", origin);
} else {
headers.add("Access-Control-Allow-Origin", "");
}
headers.add("Vary", "Origin");
}
headers.add("Access-Control-Allow-Credentials", "true");
headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
headers.add("Access-Control-Allow-Headers",