From 83a8f2baa72cad6a56047d8d9f3e48f5d66a99ca Mon Sep 17 00:00:00 2001 From: Stan Silvert Date: Tue, 6 Apr 2021 02:44:37 -0400 Subject: [PATCH] Allow four ways to set location of keycloak server. (#482) * Allow four ways to set location of keycloak server. * Make it work for devs on Keycloak 12 and below. --- src/context/auth/keycloak.ts | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/src/context/auth/keycloak.ts b/src/context/auth/keycloak.ts index 89a8ed4ff1..e98da620c3 100644 --- a/src/context/auth/keycloak.ts +++ b/src/context/auth/keycloak.ts @@ -6,23 +6,46 @@ export default async function (): Promise { const kcAdminClient = new KcAdminClient(); - const authContext = "/auth"; - const keycloakAuthUrl = window.location.origin + authContext; - const devMode = !window.location.pathname.startsWith("/adminv2"); try { await kcAdminClient.init( { onLoad: "check-sso", pkceMethod: "S256" }, { - url: devMode ? "http://localhost:8180/auth" : keycloakAuthUrl, + url: keycloakAuthUrl(), realm: realm, clientId: "security-admin-console-v2", } ); kcAdminClient.setConfig({ realmName: realm }); - kcAdminClient.baseUrl = authContext; + + // we can get rid of devMode once developers upgrade to Keycloak 13 + const devMode = !window.location.pathname.startsWith("/adminv2"); + kcAdminClient.baseUrl = devMode ? "/auth" : keycloakAuthUrl(); } catch (error) { alert("failed to initialize keycloak"); } return kcAdminClient; } + +const keycloakAuthUrl = () => { + // Eventually, authContext should not be hard-coded. + // You are allowed to change this context on your keycloak server, + // but it is rarely done. + const authContext = "/auth"; + + const searchParams = new URLSearchParams(window.location.search); + + // passed in as query param + const authUrlFromParam = searchParams.get("keycloak-server"); + if (authUrlFromParam) return authUrlFromParam + authContext; + + // dev mode + if (!window.location.pathname.startsWith("/adminv2")) + return "http://localhost:8180" + authContext; + + // demo mode + if (searchParams.get("demo")) return "http://localhost:8080" + authContext; + + // admin console served from keycloak server + return window.location.origin + authContext; +};