Skip to content

Blog

Keycloak CORS errors: causes and fixes

Why the browser blocks calls to Keycloak with a CORS error, how Web origins work, how to find the real status code behind it, and how to fix each cause.

Author
The RealmDeploy team
Published

A CORS error is the browser refusing to hand a response to your JavaScript. The request often reached Keycloak and got an answer. The browser then looked for the right Access-Control-* headers, did not find them, and blocked the result.

Single-page apps see this most. They exchange the authorization code at the token endpoint, refresh tokens and call userinfo straight from the browser. Backend apps never see CORS errors, because CORS is a browser rule.

The hard part is that the browser hides the real problem. A missing Web origin, a 401, a 502 from a proxy and a typo in the URL can all end up as the same red line in the console.

What you see

In the browser console, the message comes from the browser, not from Keycloak. The wording differs between browsers. Chrome and Edge usually say the request was blocked by CORS policy because no Access-Control-Allow-Origin header is present. Firefox calls it a cross-origin request blocked by the same origin policy.

In the network tab, the failing request often shows a status such as 200, 400, 401, 403 or 502, or no status at all. The response body is not readable from JavaScript.

On the Keycloak side, a disallowed origin is quiet by default. With debug logging for the CORS code, the server log shows this line (from DefaultCors in Keycloak 26.8.2):

Invalid CORS request: origin {0} not in allowed origins {1}

The two placeholders are filled with the origin the browser sent and the origins Keycloak allows for that client.

Causes, most common first

  1. The app's origin is not in the client's Web origins. The token request fails while the login redirect works. The debug log shows the line above.
  2. Web origins lists a path or a trailing slash. An origin is only scheme, host and port. https://app.example.com/ does not match https://app.example.com.
  3. The real error is a 4xx or 5xx without CORS headers. The network tab shows 400, 401 or 502 next to the CORS message.
  4. A proxy strips, adds or duplicates Access-Control-* headers. The response has two Access-Control-Allow-Origin values, or none, while Keycloak's own log looks fine.
  5. The code calls the authorization endpoint with fetch. The request goes to /protocol/openid-connect/auth from JavaScript instead of a full page redirect.
  6. The wrong host or realm is called. The URL in the network tab has an old host, an /auth prefix or a realm name with different case.

How Keycloak decides on CORS

Keycloak sends CORS headers only on endpoints that browsers call with fetch or XMLHttpRequest. In Keycloak 26.8.2:

EndpointHow the allowed origins are chosen
Token endpointThe Web origins of the client that authenticates
Userinfo, account REST API, admin REST APIThe allowed-origins claim in the access token, or the client's Web origins when the claim is missing
Discovery document and JWKS (certs)Any origin
Authorization endpoint (/auth)None: it is a browser redirect, not an API

The allowed-origins claim comes from the web-origins client scope. If you removed that scope from a client, its tokens no longer carry the claim.

Web origins on the client accepts three kinds of values. The admin console's help text puts it this way: to permit all origins of Valid Redirect URIs, add +, which does not include the * wildcard; to permit all origins, add * explicitly.

  • Exact origins such as https://app.example.com. This is the safest choice.
  • + takes the origins of the client's Valid redirect URIs. It is usually right for a single-page app whose redirect URI lives on the same origin.
  • * allows every origin. Avoid it on any client that is not purely public test code.

There is one detail that confuses many people. For preflight (OPTIONS) requests, Keycloak answers with the origin it was sent. The preflight succeeds, and the real request that follows is the one that fails. So a green preflight does not prove the origin is allowed.

On the token endpoint, Keycloak checks the origin after it identifies the client. A disallowed origin gets a 403 without CORS headers. The browser then reports it as a CORS error, and your code never sees the 403.

Diagnose it step by step

  1. Open the network tab in the browser's developer tools and reproduce the error. Select the failing request, not the console message.
  2. Read the status code. A 401 or 400 means Keycloak rejected the request for another reason. A 502 or 504 means the proxy failed. A 403 from the token endpoint, or a successful status with missing headers, points at Web origins.
  3. Copy the Origin request header exactly. Compare it with the client's Web origins, character for character, including scheme and port.
  4. Check the response headers. Look for one Access-Control-Allow-Origin that equals the origin, and Access-Control-Allow-Credentials if cookies are involved.
  5. Turn on saved events in the admin console (Realm settings, Events, User events settings) and repeat. A CODE_TO_TOKEN_ERROR or REFRESH_TOKEN_ERROR event shows the real reason, such as invalid_grant.
  6. Raise the log level for CORS for a short time and look for the line shown above.
  7. Reproduce with curl. Send the same request with an Origin header and read every response header.
  8. Decode the access token for userinfo or admin API calls. Check that allowed-origins holds your app's origin.
curl -s -o /dev/null -D - \
  -H 'Origin: https://app.example.com' \
  -d 'grant_type=refresh_token' \
  -d 'client_id=my-spa' \
  -d "refresh_token=$REFRESH_TOKEN" \
  https://auth.example.com/realms/acme/protocol/openid-connect/token

If the headers come back without Access-Control-Allow-Origin, the origin is not allowed for that client. If they come back with it, the browser problem is somewhere else, often in a proxy.

To log the CORS decision on a self-hosted server:

bin/kc.sh start --log-level=info,org.keycloak.services.cors:debug

Turn it back off when you are done. Debug logs are noisy.

Fixes

Add the exact origin

In the admin console, open Clients, select the client, and set Web origins to the app's origin. Or use kcadm.sh:

kcadm.sh update clients/$CLIENT_UUID -r acme \
  -s 'webOrigins=["https://app.example.com"]'

Use the client's internal id, not its client id, in the path. List both origins if the app runs on more than one, for example a staging host and a production host.

Use + for a single-page app on one origin

If the redirect URI is https://app.example.com/callback, then + allows https://app.example.com. It keeps the two lists in step when you add a redirect URI later.

Fix the error behind the CORS message

When the network tab shows 400 or 401, treat it as that error. Common ones are an expired refresh token (invalid_grant), a wrong client id, or a confidential client used from the browser. A browser app should be a public client with PKCE. It should never hold a client secret.

When the network tab shows 502 or 504, the request never got a Keycloak answer. Look at the proxy. See our post on 502 errors and redirect loops behind a proxy.

Let Keycloak own the CORS headers

If a proxy in front of Keycloak also adds CORS headers, the browser may get two Access-Control-Allow-Origin values and reject both. Remove CORS handling from the proxy for Keycloak's paths. In nginx, that means no add_header Access-Control-* lines in the Keycloak locations, and no proxy_hide_header for those headers either.

location /realms/ {
    proxy_pass http://keycloak:8080;
    # No add_header Access-Control-* here: Keycloak sets them per client.
}

Redirect to the authorization endpoint

Sign-in starts with a full page redirect, not a fetch. With the keycloak-js adapter, call login() and let it navigate:

import Keycloak from 'keycloak-js';

const keycloak = new Keycloak({
  url: 'https://auth.example.com',
  realm: 'acme',
  clientId: 'my-spa',
});

await keycloak.init({ onLoad: 'check-sso', pkceMethod: 'S256' });
if (!keycloak.authenticated) {
  await keycloak.login();
}

The adapter then calls the token endpoint itself. That call is the one that needs Web origins.

Call the right address

Check the url and realm your app uses against the discovery document. In Keycloak 17 and later, the default path has no /auth prefix. A realm named Acme is not the realm acme.

On RealmDeploy

Web origins, redirect URIs and client settings are yours. You change them in your own admin console, and the fixes above apply as written. We do not add CORS headers at the gateway in front of your Keycloak, so Keycloak's own headers reach the browser unchanged. If the network tab shows a 502 or 504 from your hostname, write to us from the dashboard or with the contact form, with the time and the request URL.

Tools that help

  • CORS checker: paste the request and response headers from the network tab and see which CORS rule fails.
  • Web origins helper: work out the Web origins value for a client from its redirect URIs.
  • JWT decoder: read the allowed-origins claim in an access token.
  • OIDC discovery viewer: check the token and userinfo endpoints your app should call.
  • Redirect URI matcher: test which redirect URIs, and so which + origins, a client allows.
  • Realm endpoints: list a realm's endpoint URLs to compare with what your app calls.