~/blog/self-hosted-keycloak-sso-for-five-products
Self-hosted Keycloak for five products: realms, tokens, deploys and backups
How I put one self-hosted Keycloak in front of five products on different domains: one realm with a client per product, realm-as-code, a token-exchange contract every backend implements, 2FA that social login can't skip, health-gated deploys, and backups you have actually restored.
On this page
At VarnueAI we sell five products: AssetSphere, VarnueVedAI (web and mobile), Vitye AI, LeadOps, and Chem Gems, a customised AssetSphere for one client. Each lives on its own domain, and until recently each had its own login. I replaced the five logins with one self-hosted Keycloak at auth.varnueai.com, behind a marketplace called Edge. The business side is in the case study. This post covers the engineering: how the realm is laid out, how products trust the tokens, and how you run an identity server you can't afford to lose.
Why self-host, and why Keycloak
The requirements were email + password, Google and Microsoft sign-in, authenticator-app 2FA, recovery codes, a password policy, brute-force lockout, and one sign-out across every product. Keycloak does all of that out of the box, it speaks standard OIDC so every product can use stock libraries, and it runs in one container next to one Postgres. Self-hosting kept user data on infrastructure the company controls, with no per-user pricing as the suite grows.
The cost of self-hosting is that backups, upgrades and recovery are yours. Most of this post is about that part.
One realm, one client per product
The first decision is how many realms. A Keycloak SSO session belongs to one realm, so "sign in once, use every product" means one realm (varnueai) for the whole suite. Each product gets its own client:
# realm/varnueai.yaml (trimmed)
clients:
- clientId: assetsphere-web
publicClient: true
standardFlowEnabled: true # Authorization Code
implicitFlowEnabled: false
directAccessGrantsEnabled: false # no password grant
redirectUris: ["$(env:ASSETSPHERE_WEB_URL)/*"]
webOrigins: ["+"] # = the redirect URIs' origins
attributes:
pkce.code.challenge.method: S256
backchannel.logout.url: "$(env:ASSETSPHERE_BACKCHANNEL_LOGOUT_URL:-)"
backchannel.logout.session.required: "true"
protocolMappers:
- name: audience-assetsphere-api
protocol: openid-connect
protocolMapper: oidc-audience-mapper
config:
included.custom.audience: assetsphere-api
access.token.claim: "true"
id.token.claim: "false"Three properties matter:
- Public clients with PKCE. SPAs can't keep a secret, so there is none. PKCE (S256) protects the code exchange instead, and the password and implicit grants are off.
- An audience per product. Each client's access tokens carry
aud = <product>-api. A token minted for Vitye is rejected by AssetSphere's backend, even though the same person and the same session produced both. - Environment values substituted at import. The same YAML serves
auth.varnue.com(dev/UAT) andauth.varnueai.com(production). Only.envdiffers.
The internal staff admin panel is deliberately not a client. Staff accounts and customer accounts never share an identity store.
Realm as code
Nobody configures the realm by clicking. realm/varnueai.yaml holds the realm settings, authentication flows, required actions, identity providers and every client, and keycloak-config-cli applies it on every deploy:
# compose.yml
config-cli:
image: adorsys/keycloak-config-cli:6.5.1-26.5.5
profiles: ["config"] # only runs when deploy.sh asks for it
environment:
KEYCLOAK_URL: http://keycloak:8080
IMPORT_FILES_LOCATIONS: /config/*.yaml
IMPORT_VARSUBSTITUTION_ENABLED: "true"
IMPORT_REMOTESTATE_ENABLED: "true" # only purge what config-cli itself created
volumes:
- ./realm:/config:roTwo rules keep this safe:
- Remote state on. config-cli only deletes resources it created, so an import can never wipe users or sessions.
- Idempotency is tested, not assumed. CI boots Keycloak and Postgres, applies the realm twice, then runs an end-to-end test: register, verify the email through a mail catcher, check the token contract, import a user. If the second import changes anything or the flow breaks, the pull request fails.
The first deploy uses the bootstrap admin to import. After that, a dedicated client_credentials service account does it, and the bootstrap admin is never used again.
The contract every backend implements
Products keep their own sessions, roles and organizations. Keycloak only says who someone is. The glue is one endpoint per product backend, POST …/sso/exchange, which receives a Keycloak access token and checks it in this order:
- Signature against
<issuer>/protocol/openid-connect/certs, RS256 only (never trust thealgheader). issequals the configured issuer exactly. Dev tokens must not work in production.audcontains the product's audience, andazpis the product's client.typisBearer;subandemailare present;email_verifiedistrue.- Find the user by
sub. Otherwise link a pending invitation with the same verified email (case-insensitive), or answer403 NO_ACCOUNTso the SPA can offer Create your organization. - Issue the product's own 15-minute session token, carrying
kc_suband the Keycloak session idsid.
Lifetimes are layered on purpose: a Keycloak access token lives 5 minutes, the SSO session 8 hours idle and 7 days at most, and a product session 15 minutes. A product session can't outlive the Keycloak session by more than 15 minutes, because renewing it needs a fresh Keycloak token.
Moving between products is silent. keycloak-js runs check-sso in a hidden iframe on /silent-check-sso.html, finds the session and gets a token without a prompt. That page must be framable by its own origin: X-Frame-Options: SAMEORIGIN, not DENY. A security-hardened Nginx default that sends DENY everywhere quietly breaks silent SSO.
Flows: 2FA that social login can't skip
Built-in flows cover most of it. Two needed care.
Recovery codes. The browser flow's conditional 2FA step offers the authenticator code or a recovery code, but only for users who enrolled one. Users enrol both from Keycloak's account page, which every product links to.
Google and Microsoft. A brokered login skips the browser flow, so by default it also skips 2FA. The realm adds a post broker login flow that asks for the OTP or a recovery code whenever the user has one configured:
identityProviders:
- alias: google
trustEmail: true # Google verifies its emails
firstBrokerLoginFlowAlias: first broker login
postBrokerLoginFlowAlias: post broker 2FA
- alias: microsoft
trustEmail: false # the tenant controls the address
firstBrokerLoginFlowAlias: first broker login
postBrokerLoginFlowAlias: post broker 2FAThe first broker login flow is what prevents account takeover. If someone arrives through Microsoft with an email that already has an account, Keycloak makes them prove they own that account (password or email link) before it links anything. Microsoft emails are not trusted as verified, because whoever controls the Azure tenant controls the address.
Sign out once, everywhere
keycloak.logout() ends the SSO session. Other open tabs notice within seconds through keycloak-js's session-status iframe. Backends find out through back-channel logout: Keycloak POSTs a signed logout token to each client's backchannel.logout.url, and the backend stores the sid and refuses every session token that carries it.
Running it: image, network, Nginx
The image bakes the theme and build-time options in, so the container starts with --optimized and skips the build step on every boot:
ARG KEYCLOAK_VERSION=26.5.5
FROM quay.io/keycloak/keycloak:${KEYCLOAK_VERSION} AS builder
ENV KC_DB=postgres KC_HEALTH_ENABLED=true
COPY themes/varnueai /opt/keycloak/themes/varnueai
RUN /opt/keycloak/bin/kc.sh build
FROM quay.io/keycloak/keycloak:${KEYCLOAK_VERSION}
COPY --from=builder /opt/keycloak/ /opt/keycloak/
CMD ["start", "--optimized"]On the VM, each environment is one Compose project:
- Postgres has no published port. It is reachable only on the environment's private Docker network.
- Keycloak binds to
127.0.0.1: port 8080 for traffic, port 9000 for management and health. Host Nginx terminates TLS and forwards withX-Forwarded-*headers (KC_PROXY_HEADERS=xforwarded). - Nginx returns 404 for
/admin/, themasterrealm and/health/*. The admin console is reached through an SSH tunnel, never the internet. - The healthcheck has no curl. The Keycloak image ships without curl or wget, so the probe speaks HTTP over bash's
/dev/tcp:
healthcheck:
test:
- CMD-SHELL
- >-
exec 3<>/dev/tcp/127.0.0.1/9000 &&
printf 'GET /health/ready HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n' >&3 &&
grep -q 'HTTP/1.1 200' <&3Deploying a stateful identity server
Every other VarnueAI service deploys blue/green. Keycloak deliberately doesn't. It is one stateful instance, and a version upgrade migrates its database, so two versions can't serve the same data side by side. Instead, deploy.sh makes an in-place restart safe:
- Validate
.envbefore touching anything: required values, SMTP (registration and password reset depend on it), real credentials for any enabled identity provider, nolocalhostredirect origins in production, and an off-VM backup target in production. - Remember the running image and take a pre-deploy backup. If the backup fails, stop. Nothing has changed.
- Pull the new image and restart.
- Health gate: poll
/health/readyfor up to 3 minutes. If it never gets healthy, start the previous image again. - Apply the realm with config-cli.
- Smoke test the issuer: fetch
/.well-known/openid-configurationand compareissuerwith what every product backend pins. A wrongKC_HOSTNAMEwould otherwise break every product's token validation at once.
The image follows the same pipeline as everything else: merges to main build dev-<sha> and deploy to auth.varnue.com, and a manual dispatch retags that exact image prod-<sha> for auth.varnueai.com.
Upgrades pin two versions together: the Keycloak base image and the matching config-cli image. A version bump goes to dev first, gets the checklist below, then is promoted.
Backups you have actually restored
Every product stores Keycloak user ids in a keycloak_sub column. If the Keycloak database is lost and rebuilt, every user gets a new id and every link across five products breaks. This database is the most important thing on the server.
scripts/backup.sh runs nightly from a systemd timer and before every deploy:
docker exec "$DB_CONTAINER" pg_dump -U keycloak -d keycloak -Fc > "$dump.tmp"
# a dump pg_restore can't list is not a dump
docker exec -i "$DB_CONTAINER" pg_restore --list < "$dump.tmp" > /dev/null
mv "$dump.tmp" "$dump" && chmod 600 "$dump"
bash -c "${BACKUP_UPLOAD_CMD//\{\}/$dump}" # copy off the VM; required in production
find "$BACKUP_DIR" -name "keycloak-$ENV-*.dump" -mtime +14 -delete# varnue-sso-backup@.timer
[Timer]
OnCalendar=*-*-* 02:30:00
RandomizedDelaySec=600
Persistent=true # a night the VM was down runs at next bootA backup you haven't restored is a hope, so scripts/restore.sh has two modes:
--drillrestores the dump into a throwaway Postgres container, prints row counts for realms, users, clients and credentials, and deletes the container. Nothing live is touched. It runs before go-live and after every upgrade.--replacestops Keycloak, asks for confirmation, restores into the live database and starts Keycloak again.
There is also a documented last resort: if the database is lost with no backup, re-import users, set keycloak_sub to NULL in every product, and let each product re-link by verified email at next sign-in.
Moving existing users in
Every product already had users. The switch-over for each product, on UAT first, then production:
- Deploy the backend with SSO configured and the old login still working.
- Export users with a per-product SQL query and import them into Keycloak without passwords. Write each new
subback into the product's table (keycloak_subbackfill), with a dry run and an audit query first. - Rebuild the frontend with the Keycloak settings and send "set up your sign-in" emails.
- After a 48–72 hour soak, turn off the legacy login routes.
- Point back-channel logout at the backend.
Production accounts were copied from UAT with their ids, so links verified on UAT stayed valid in production. The import service account is switched off afterwards, and deploy.sh warns while it is enabled.
Go-live checklist
Run once per environment, by hand:
- Register, receive the verification email, sign in.
- Enrol Google Authenticator and Microsoft Authenticator; the next sign-in asks for the code.
- Sign in with a recovery code; a used code is rejected the second time.
- Reset a password from the sign-in page.
- Sign in with Google as a new user, and as a user with 2FA (Keycloak asks for the code after Google).
- Sign in with Microsoft using an email that already has an account: Keycloak must ask for proof of ownership, never link silently.
/admin/,/realms/master/and/health/readyreturn 404 from the internet.- A product container can reach the issuer over the public hostname (hairpin NAT can bite here).
restore.sh --drillpasses on last night's dump.
What I'd tell myself on day one
- One realm if you want SSO across products. Realms are isolation boundaries, not folders.
- Pin the issuer and the audience in every backend. Most token bugs are a token accepted somewhere it shouldn't be.
- Treat the realm as code from the first commit. Console clicks are drift you will lose on the next deploy.
- Social login is a different flow. Check that 2FA and account linking behave the way you think.
- Your identity database is the product's root of trust. Back it up off the machine, and rehearse the restore before you need it.
Linked from
Keep reading
Monthly notes
Get the next one in your inbox.
One email a month on infrastructure, backend design and applied AI. No noise, unsubscribe any time.
Comments (0)
name + comment · no login