Keycloak GET请求未添加CORS Origin头但OPTIONS正常的原因排查
Keycloak 19.0.1 GET请求CORS头缺失问题排查
Firefox报错信息:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://<publichostname>/realms/<realm>/account. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
已完成的配置操作:
- 客户端Web Origins已添加
https://127.0.0.1:3000、网站公网域名,测试过*、+通配符,同时给account客户端做了相同配置 - 重定向URI配置无误
异常现象:
- 前置OPTIONS请求能返回正确的
Access-Control-Allow-Origin头,但紧随其后的GET请求无该头 - 本地开发环境和线上部署环境均触发该CORS错误
网络链路:终端用户 → Cloudflare(已设置开发模式,无缓存)→ NGINX(仅配置SSL、反向代理,对/metrics和/health路径返回403,未添加额外响应头)→ Keycloak 19.0.1(Quarkus版本)
相关配置与代码片段
Keycloak启动配置(systemd服务片段)
ExecStart=/opt/keycloak/bin/kc.sh --config-file=/etc/keycloak/keycloak.conf start
keycloak.conf核心配置
db=postgres db-username=<redacted> db-password=<redacted> db-url=jdbc:postgresql://<redacted>/keycloak_auth health-enabled=true metrics-enabled=true proxy=edge hostname=<publichostname> hostname-admin=<publichostname> hostname-strict-backchannel=true http-host=<internal ip> log=console,file log-console-color=true log-file=/var/log/keycloak.log log-level=info
注:keycloak.log仅输出启动日志,无CORS相关错误信息
auth.ts客户端初始化代码
import { browser } from '$app/env'; import Keycloak from 'keycloak-js'; export let keycloak; if (browser) { keycloak = new Keycloak({ url: 'https://<publichostname>/', realm: '<redacted>', clientId: '<redacted>', }); await keycloak .init({ enableLogging: true }) .then(function (auth) { console.log('Keycloak Initalised ' + auth); }) .catch(function (error) { console.log('Keycloak Failed to Init: ' + error); }); } else { console.log('Cannot auth in non-browser environment.'); }
index.svelte触发错误的业务代码
// Auth async function auth() { if (browser) { const auth = await import('$lib/components/auth/auth'); auth.keycloak.login(); } else { console.log('Cannot auth in non-browser environment.'); } } async function logout() { if (browser) { const auth = await import('$lib/components/auth/auth'); auth.keycloak.logout(); } else { console.log('Cannot auth in non-browser environment.'); } } async function isLoggedIn() { if (browser) { const auth = await import('$lib/components/auth/auth'); console.log(await auth.keycloak.loadUserProfile()); return await auth.keycloak.authenticated; } else { console.log('Cannot auth in non-browser environment.'); return false; } }
CORS错误在调用isLoggedIn()时触发,页面会根据该函数返回值切换登录/登出按钮。已查阅大量技术论坛及Stack Overflow帖子,多数解决方案为添加域名到Web Origins,但该操作已完成,怀疑遗漏了某些基础配置,寻求解决思路。
内容的提问来源于stack exchange,提问作者Piklet
相关产品推荐
相关产品推荐

