Node.js – Keycloak CORS issue when being redirected to login

corsexpresskeycloaknode.js

I am trying to get the nodeJS keycloak adapter working with my Express application, but am facing a CORS issue when it tries to redirect to the login page for routes I have protected with the keycloak middleware:

XMLHttpRequest cannot load
http://192.168.132.44:8080/auth/realms/Actora/protocol/openid-connect/auth?client_id=actora-test&state=0e9c9778-c41b-4aa8-8052-d0f0125045ac&redirect_uri=http%3A%2F%2Flocalhost%3A5001%2Fauth%2Fchecktoken%3Fauth_callback%3D1&scope=openid&response_type=code.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:5001' is therefore not allowed
access.

In my keycloak client settings I have added a single value of '*' to the Web Origins config section.

I have also enabled cors on my node express application using the node cors library, following this express guide here

var cors =  require('cors'),
  app = express();

app.use(cors());
app.options('*', cors()); //enable for all pre-flight requests

I using version 3.2.1 of keycloak in case that makes any difference (I see a new version is out as an RC)

Has anyone faced similar issues and managed to resolve? I have been digging through many JBOSS mailing list threads and other stackoverflows, and all seem to suggest its as simple as adding the '*' entry to the web origins config section for the client on the keycloak admin site but this is not the case for me.

Thanks

Best Answer

I am also working on this issue with mindparse.

I think the key issue here is that the keycloak server is not responding with any ACCESS-CONTROL-ALLOW-ORIGIN headers despite the fact that he has correctly configured the "web Origins" setting in the keycloak admin portal.

A more in depth flow of the process is:

  1. The user attempts to call a keycloak secured route on a node express server
  2. Keycloak middleware detects that the user is not authenticated and responds to the request with a 302 (redirect) to a custom login page hosted by the keycloak server.
  3. The browser sends an OPTIONS request to the keycloak server to check if it is because it is a cross origin request.
  4. The keycloak servers response DOES NOT include the ACCESS-CONTROL-ALLOW- ORIGIN header to tell the browser that it has permission to make this request.
  5. The browser then reads this response and therefore does not make the follow up request because it did not pass the access control allow origin checks
Related Topic