Skip to content

Putting an app behind Keycloak login

Some apps have no login of their own. The components/auth-proxy component puts a Keycloak sign-in in front of such an app: only members of one Keycloak group in the skatzi realm get through. It runs oauth2-proxy as a reverse proxy, one instance per app, in the app's namespace.

browser ──▶ shared-gateway ──▶ HTTPRoute <app>-auth-proxy ──▶ <app>-auth-proxy ──▶ app Service
                                                                   │
                                                                   └─ sign-in: keycloak.prod.skatzi.com/realms/skatzi

Why a proxy, not forward-auth

The shared gateway is Cilium (1.18) with the Gateway API standard channel (v1.2). Neither has a way to ask an auth service before routing a request:

  • Cilium's Gateway API translation handles only the RequestHeaderModifier, ResponseHeaderModifier, RequestRedirect, URLRewrite and RequestMirror HTTPRoute filters (operator/pkg/model/ingestion/gateway.go).
  • The Gateway API ExternalAuth filter (GEP-1494) is experimental and not in the v1.2 CRDs we install.

So the app's HTTPRoute points at the proxy, and the proxy forwards signed-in requests to the app's ClusterIP Service. The app itself gets no route on the gateway.

What the component does

Resource Purpose
ExternalSecret <app>-auth-proxy Client secret and cookie secret from OpenBao
Deployment <app>-auth-proxy oauth2-proxy, provider keycloak-oidc, PKCE, --allowed-group
Service <app>-auth-proxy Port 80 to the proxy
HTTPRoute <app>-auth-proxy https://<host>/ to the proxy
HTTPRoute <app>-auth-proxy-redirect http://<host>/ redirected to HTTPS

oauth2-proxy passes the user to the app in X-Forwarded-User, X-Forwarded-Email, X-Forwarded-Preferred-Username and X-Forwarded-Groups. Its own endpoints live under /oauth2/ (sign-out: /oauth2/sign_out).

The component is configured with Flux postBuild.substitute variables:

Variable Meaning Example
auth_proxy_app Name prefix of the resources, and the Keycloak client ID helloweekly
auth_proxy_host Public hostname helloweekly.skatzi.com
auth_proxy_upstream The app's ClusterIP Service http://helloweekly:8080
auth_proxy_group Keycloak group whose members may sign in (name, no leading /) helloweekly
auth_proxy_openbao_path OpenBao key under clusters/ with the two secrets hetzner-mgmt/helloweekly/auth-proxy

Steps

1. Keycloak: client, mappers and group (by hand)

In the admin console, realm skatzi:

  1. Clients → Create client
    • Client type OpenID Connect, Client ID = auth_proxy_app (e.g. helloweekly).
    • Client authentication on (a confidential client).
    • Authentication flow: Standard flow only; turn off Direct access grants.
    • Valid redirect URIs: https://<host>/oauth2/callback.
    • Web origins: https://<host>.
  2. On the client: Credentials → copy the Client secret.
  3. On the client: Client scopes → <client>-dedicated → Configure a new mapper:
    • Group Membership: name groups, Token Claim Name groups, Full group path off, Add to ID token, access token and userinfo on. This is the same mapper the realm's other clients use; the proxy checks auth_proxy_group against this claim.
    • Audience: name aud-mapper-<client>, Included Client Audience = the client, Add to ID token and access token on (as the oauth2-proxy Keycloak guide asks).
  4. Groups → Create group named auth_proxy_group, and add the people who may use the app. Each of them needs an e-mail address marked Email verified: oauth2-proxy refuses sign-ins with an unverified address.

The realm is imported from components/keycloak/base/skatzi-realm.yaml only when it is first created, so clients added in the console are not in git.

2. OpenBao: the two secrets

bao kv put clusters/hetzner-mgmt/<app>/auth-proxy \
  client-secret="<client secret from step 1>" \
  cookie-secret="$(python3 -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())')"

The cookie secret must decode to 16, 24 or 32 bytes; the command above is the one the oauth2-proxy docs give.

3. Platform: one Flux Kustomization for the app

Add it to the app's cluster/<cluster>/<app>/kustomization.yaml, next to the app's own GitRepository and Kustomization:

---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: helloweekly-auth-proxy
  namespace: flux-system
spec:
  interval: 5m0s
  path: ./components/auth-proxy
  prune: true
  targetNamespace: helloweekly-prod   # the app's namespace
  sourceRef:
    kind: GitRepository
    name: ${git_source_repository}
  dependsOn:
    - name: helloweekly             # creates the namespace and the app Service
    - name: shared-gateway
  postBuild:
    substitute:
      auth_proxy_app: helloweekly
      auth_proxy_host: helloweekly.skatzi.com
      auth_proxy_upstream: http://helloweekly:8080
      auth_proxy_group: helloweekly
      auth_proxy_openbao_path: hetzner-mgmt/helloweekly/auth-proxy
  healthChecks:
    - apiVersion: apps/v1
      kind: Deployment
      name: helloweekly-auth-proxy
      namespace: helloweekly-prod

Then add the hostname to the certificate dnsNames in cluster/<cluster>/gateway-system/kustomization.yaml.

4. The app repository

The app's own manifests must not have an HTTPRoute for the host: anything routed straight to the app Service skips the sign-in. The app keeps a plain ClusterIP Service, which the proxy reaches inside the namespace.

5. Optional: API access with a token, without the sign-in

Agents and scripts cannot use the browser sign-in. If the app checks its own bearer tokens, the cluster can send API requests that carry one straight to the app, with a patch on the proxy's HTTPRoute in the Flux Kustomization from step 3. Helloweekly does this (cluster/hetzner-mgmt/helloweekly/kustomization.yaml, Helloweekly task #1786):

  patches:
    - target:
        kind: HTTPRoute
        name: .*-auth-proxy   # matched before substitution; leaves out -redirect
      patch: |-
        - op: add
          path: /spec/rules/-
          value:
            matches:
              - path:
                  type: PathPrefix
                  value: /api/
                headers:
                  - type: RegularExpression
                    name: Authorization
                    value: "^Bearer .+"
            backendRefs:
              - name: helloweekly
                port: 8080
  • The longer path prefix wins, so /api/ requests with the header go to the app, and every other request still goes to the proxy. Cilium sorts the Envoy routes by prefix length (envoy_virtual_host.go) and supports RegularExpression header matches (gateway.go, toHeaderMatch).
  • The app must reject every request with an Authorization header that is not a valid token. Anyone on the internet can send such a header and reach the app this way. Requests without the header still come only through the proxy. The proxy adds no Authorization header of its own, because the component sets neither --basic-auth-password nor --pass-authorization-header.
  • In-cluster agent runners also need the app's pod in their egress policy (cluster/hetzner-mgmt/agent-runners/namespace/cilium-network-policy.yaml). Otherwise the gateway answers 403 Access denied, see the agent-runner component.

Checking it

  • https://<host>/ sends you to the Keycloak sign-in, and back to the page you asked for.
  • A user outside the group gets oauth2-proxy's 403 page after signing in.
  • kubectl --context <context> -n <namespace> logs deploy/<app>-auth-proxy shows each request with the user; <context> is the kubeconfig context of the cluster that runs the app (rules of engagement, rule 8).
  • With step 5: curl -H "Authorization: Bearer <token>" https://<host>/api/... reaches the app, and an invalid token gets the app's 401, not the sign-in page.