Keycloak CORS issue when being redirected to login

Viewed 41175

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

5 Answers

Just put the url of your app like "http://localhost:8081" in "Web Origins" field of client settings in Keycloak.

I had the exact same problem. I am using Keycloak 6.0.1

In my case, I had to add "enable-cors": true in keycloak.json in my Java backend server.

Afterward, I had another issue: 401 UNAUTHORIZED. This post solved the problem

I also faced CORS issues while trying to connect to KeyCloak, even though I had correctly filled out the "Web Origins" url.

Turned out I accidentally connected to the wrong App (Client) and tenant (Realm), therefore not passing the CORS checks. Pointing to the right app and tenant fixed my problem.

Web Origins must be set correctly for a configured client, yes, but it too has some pitfalls because a "+" setting depends on other values.

E.g., I had this wrong configuration for local tests:

Root URL: http://localhost:3000/
Valid redirect URIs: *
Web Origins: +

... and it failed with a CORS issue like you describe.

The issue lay with the other two settings, so this is correct and works now:

Root URL: http://localhost:3000
Valid redirect URIs: /*
Web Origins: +

(The KeyCloak UI is a usability nightmare on many fronts, imo, this is just one pitfall)

Related