I have added a CorsFilter implementing ContainerRequestFilter
and ContainerResponseFilter
to my jax-rs backend API. Pretty much a copy/paste of other CorsFilters found on Stackoverflow and other guides. When I do requests from the browser, the preflight OPTIONS requests do not hit the CorsFilter(tested with logging and debug breakpoints), however my GET and POST requests hits the CorsFilter.
Why isn’t the preflight OPTIONS requests hitting my CorsFilter?
@Provider
@PreMatching
public class CorsFilter implements ContainerRequestFilter, ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext request) throws IOException {
if (isPreflightRequest(request)) {
request.abortWith(Response.ok().build());
}
}
private static boolean isPreflightRequest(ContainerRequestContext request) {
return request.getHeaderString("Origin") != null && request.getMethod().equalsIgnoreCase("OPTIONS");
}
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
final String origin = request.getHeaderString("Origin");
if (origin == null) {
return;
}
if (isPreflightRequest(request)) {
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
response.getHeaders().add("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Accept-Version, Content-MD5, CSRF-Token, Content-Type");
}
/* Allow every Origin */
response.getHeaders().add("Access-Control-Allow-Origin", origin);
}
}
Have read that some think that because the application is secured with Keycloak, and the preflight OPTIONS requests does not contain authorization headers, the request is passed to authenticate, which is triggered before the CorsFilter.
Have tried to disable auth for OPTIONS requests in the web.xml
without success.
<security-constraint>
<web-resource-collection>
<web-resource-name>Public</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>OPTIONS</http-method>
</web-resource-collection>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>Restricted Access</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method-omission>OPTIONS</http-method-omission>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
Have also tried, without success:
- With
@Priority(1)
- With and without
@PreMatching
- Tried different
web.xml
setups to disable auth for OPTIONS