(Note: this behavior has been reproduced in keycloak tomcat valve 6.0.1)
[Updated to include solution]
After much experimentation, it appears that the problem is this:
Keycloak sends back a 401 response to the CORS preflight (OPTIONS) request. No matter what headers you add to the preflight, an error status code (ie anything but a 200-series response) will be considered a CORS failure.
The solution:
1) Extend Keycloak-valve's CORS support to respond with a 204 to OPTIONS, possibly by adding code as shown below. If you feel like checking it out, figuring out its mazelike architecture, and submitting a PR, that would be great. Otherwise,
2) Disable keycloak's CORS support and add a CORS valve before it in your configuration.
I disabled CORS support in the bearer-only server by setting "enable_cors: false" (or simply remove the entry). Then I created a small CORS support valve to send Access-Control-Allow- headers. Because this is a bearer-token system, it is reasonably safe to allow "*". (Also, modern browsers will not send credentials if you allow-origin "*".)
The entire CORS support valve is something along the lines of:
public void invoke(Request rqst, Response rsp) throws ...
{
HttpServletResponse response = rsp.getResponse();
HttpServletRequest request = rqst.getRequest();
if (null != request.getHeader("origin")) {
response.setHeader("Access-Control-Allow-Origin", "*");
String method = request.getMethod();
if (method.equalsIgnoreCase("options")) { // preflight?
rsp.reset();
response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
response.setHeader("Access-Control-Max-Age", "10");
response.setHeader("Access-Control-Allow-Headers", "Origin,Accept,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Your-Header-Here");
rsp.setStatus(204);
return;
}
}
getNext().invoke(rqst, rsp);
}
but you might want to write a more full-featured valve for your application.
After adding this, CORS preflight returns a 204, and then the 401/403 responses are correctly received by the requestor.
Analysis
The Keycloak valve only sends CORS headers after checking in with the Keycloak auth server. This means that any failure of networking, configuration, or token validation by the bearer-token server-side app results in error responses without any Access-Control-Allow headers, so none of the error detail is available.
The Keycloak tomcat valve does serve up detailed failure information for almost any failure. For 401 errors, this is located in the WWW-Authenticate response header, which, like most headers, is forbidden in the case of a CORS failure. However, it returns this 401 error to the OPTIONS request, which is CORS preflight, which hides it from client code. Since any configuration error (auth-server-url has the wrong port, or realm is misspelled) also triggers CORS failure, your app never sees the header.
The error is visible in the network debugging pane of some browsers, but not to Javascript.