
# Connect Keycloak

You declare the application with Keycloak, the provider we recommend to start with: a dedicated realm, a confidential client, the audience that lets an AI assistant sign in over OAuth, the users, then the variables and the switch-over order that keep you from locking yourself out. The principles are in [sign-in through an identity provider](oidc.md); this guide is the implementation for Keycloak.

## Create the realm

Create a realm reserved for the application (**Realm settings**), distinct from the `master` realm. The **issuer** is its public URL, `https://<host>/realms/<realm>`: it is the value of `OIDC_AUTH_SERVER_URL`, and it must be **the same address** seen from the browser and from the application's container (never an internal Docker network name: the provider signs its tokens with the address it was reached by). Two layouts work: Keycloak on a **sub-path of the application's domain** (issuer `<PUBLIC_URL>/auth/realms/<realm>`) or on a **separate host** (`https://auth.exemple.org/realms/<realm>`).

> **Choose the issuer once and for all.** The account is bound to the issuer + subject pair: if the address changes, nobody signs in any more, administrators included. See [Change the provider's URL](oidc.md#changer-lurl-du-fournisseur).

In the realm settings, leave **open registration closed** (User registration disabled: accounts are created by an administrator) and enable **brute-force protection** (Security defenses › Brute force detection).

## Declare the `planning-app` client

In **Clients**, create an OpenID Connect client `planning-app` (default of `OIDC_CLIENT_ID`):

| Setting | Value |
| --- | --- |
| Client authentication | on (**confidential** client) |
| Flow | Standard flow only |
| PKCE | method `S256` |
| Valid redirect URIs | `<PUBLIC_URL>/api/auth/oidc/login`, exact, no wildcard |
| Valid post logout redirect URIs | `<PUBLIC_URL>/login`, exact, no wildcard |

The addresses are exact because the `redirect_uri` follows the `Host` header: a wildcard would let an unexpected host receive the authorization code. In the **Credentials** tab, set a secret of **at least 32 characters** (`openssl rand -base64 48`): it will be `OIDC_CLIENT_SECRET`, startup being refused below that. The client must have the `profile` and `email` scopes (`OIDC_SCOPES`).

## Open the AI assistant (MCP) over OAuth

Useful only for an assistant (Claude, Le Chat) to sign in over OAuth, without an API key; otherwise it keeps the key ([Connect an AI assistant to the MCP server](../comprendre/mcp-connexion.md)).

### The `planning-mcp` audience

The application accepts at `/mcp` only tokens carrying the `OIDC_MCP_AUDIENCE` audience (`planning-mcp` by default): without this check, a token obtained for any other client of the realm would open the tools.

1. In **Clients**, create a client `planning-mcp`: nobody signs in through it, it is the "resource" the tokens designate.
2. In **Client scopes**, create a `planning-mcp` scope of type `Default` and, in its **Mappers**, an **Audience** mapper: *Included Client Audience* `planning-mcp`, added to the access token.
3. Add this scope to the **realm's default scopes**, so that clients registered later receive it.

### Dynamic client registration

Claude on the web and Le Chat register themselves (DCR). Keycloak closes it by default (**Trusted Hosts** policy). To open it without leaving it wide open, **Clients › Client registration › Anonymous access policies**:

- **Allowed Client Scopes**: only the scopes an assistant needs, `planning-mcp` included;
- **Trusted Hosts**: limit redirects to the domains of your assistants (`claude.ai`, `claude.com`, `chat.mistral.ai`) and enable "Client URIs Must Match";
- **Max Clients**: a maximum number of registered clients;
- **Consent Required**: keep consent;
- **offline_access**: do not grant it without need, so an assistant does not keep an authorisation with no time limit.

Check that a registered client receives the audience: connect the assistant, then decode its access token (or **Client scopes › Evaluate**) and look for `planning-mcp` in `aud`; without it the application answers `401`. The token is valid only for an active application account holding an administrator or organiser right in force; Keycloak roles change nothing.

## Create the users

One Keycloak user per person (**Users**): tick **Email verified** (the application links an account to an address only if the provider declares it verified, `OIDC_REQUIRE_EMAIL_VERIFIED=true`), enter the **same address** as the account in Settings › **Accounts**, set a password (or let the person choose it) and, if you wish, a second factor. The first sign-in binds the account to the issuer + subject pair. **Keycloak roles give no right**: rights are given in Settings › **Accounts**.

## Switch over without locking yourself out

1. **Create your `ADMIN` account first** in the application and check that it signs in locally (password and code, [local accounts](comptes-locaux.md)).
2. **Set the variables**:

   | Variable | Value |
   | --- | --- |
   | `OIDC_ENABLED` | `true` |
   | `OIDC_AUTH_SERVER_URL` | the issuer, `https://<host>/realms/<realm>` |
   | `OIDC_CLIENT_ID` | `planning-app` |
   | `OIDC_CLIENT_SECRET` | the client secret, 32 characters at least |
   | `OIDC_FORCE_HTTPS` | `true` behind a proxy that terminates TLS |
   | `OIDC_MCP_AUDIENCE` | `planning-mcp` (the default) |
   | `ADMIN_LOCAL_SECOURS` | absent, or `false` |

3. **Redeploy**, then test a sign-in through Keycloak with your address: the administration must open. The application retries discovery for `OIDC_CONNECTION_DELAY` (30 seconds by default), enough for Keycloak to start after it.

Local accounts stay open during the transition. The emergency account: [Choose and protect the admin login](securite-acces-administration.md#le-compte-de-secours--ne-jamais-senfermer-dehors).

## Plan the resources

- **Memory**: about 0.5 GiB. Bound its heap (`JAVA_OPTS_KC_HEAP`) and its container's limit, and let it give way before the application: on a small host, better the kernel kills Keycloak, which restarts, than the application mid-solve.
- **Database**: give it its **own database**, separate from the application's, and back it up: users, secrets and registered clients exist only there, and the application's backup does not cover it ([Back up and restore](sauvegarde-et-restauration.md)).
- **Exposure**: no admin console on the Internet. At the proxy, only `/realms/<realm>/` and `/resources/` are reachable; neither `/admin/` nor the `master` realm.

## A complete example

A real deployment, anonymised: Keycloak 26 on the `/auth` sub-path of the application's domain, with its own small PostgreSQL database, behind a reverse proxy that terminates TLS. Domain `planning.exemple.org`, secrets as `<PLACEHOLDER>`: reuse the structure, not the values.

### Keycloak and its database (Docker Compose)

Three settings to remember: the public address (`KC_HOSTNAME`, which signs the issuer), the sub-path (`KC_HTTP_RELATIVE_PATH`) and the memory limits, which lose the sign-in page before a solve.

```yaml
services:
  keycloak:
    image: quay.io/keycloak/keycloak:26.8.2
    restart: unless-stopped
    # `start`, not `start --optimized`: the official image is built neither for
    # PostgreSQL nor for /auth (BUILD options).
    command: ["start"]
    mem_limit: 768m
    # First to be killed on OOM: better to lose the sign-in page than a solve.
    oom_score_adj: 500
    security_opt: ["no-new-privileges:true"]
    environment:
      KC_DB: postgres
      KC_DB_URL: jdbc:postgresql://keycloak-db:5432/keycloak
      KC_DB_USERNAME: keycloak
      KC_DB_PASSWORD: <KEYCLOAK_DB_PASSWORD>
      # Sub-path, and PUBLIC URL with the prefix: it is what signs the issuer.
      KC_HTTP_RELATIVE_PATH: /auth
      KC_HOSTNAME: https://planning.exemple.org/auth
      # TLS terminated at the reverse proxy: Keycloak reads the scheme in X-Forwarded-*.
      KC_HTTP_ENABLED: "true"
      KC_PROXY_HEADERS: xforwarded
      KC_HEALTH_ENABLED: "true"
      # Heap at 50% of the container. MaxHeapFreeRatio under 40 requires MinHeapFreeRatio ≤ it,
      # otherwise the JVM refuses to start.
      JAVA_OPTS_KC_HEAP: "-XX:MaxRAMPercentage=50 -XX:InitialRAMPercentage=10 -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=30"
      KC_BOOTSTRAP_ADMIN_USERNAME: admin
      KC_BOOTSTRAP_ADMIN_PASSWORD: <KEYCLOAK_ADMIN_PASSWORD>
      TZ: Europe/Paris
    depends_on:
      keycloak-db:
        condition: service_healthy
    healthcheck:
      # Management port 9000, also prefixed by /auth. No curl in the image: bash redirection.
      test: ["CMD-SHELL", "exec 3<>/dev/tcp/127.0.0.1/9000 && echo -e 'GET /auth/health/ready HTTP/1.1\\r\\nHost: localhost\\r\\nConnection: close\\r\\n\\r\\n' >&3 && grep -q '\"UP\"' <&3"]
      interval: 15s
      timeout: 5s
      retries: 20
      start_period: 120s
    networks: [keycloak-internal, proxy]

  keycloak-db:
    image: postgres:19
    restart: unless-stopped
    mem_limit: 256m
    mem_reservation: 64m
    stop_grace_period: 60s
    security_opt: ["no-new-privileges:true"]
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: keycloak
      POSTGRES_PASSWORD: <KEYCLOAK_DB_PASSWORD>
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U keycloak -d keycloak"]
      interval: 5s
      timeout: 5s
      retries: 12
    volumes:
      - keycloak_data:/var/lib/postgresql
    networks: [keycloak-internal]   # never on the proxy network

networks:
  keycloak-internal:
    internal: true                  # database reachable by Keycloak alone
  proxy:
    external: true                  # the reverse proxy's
volumes:
  keycloak_data:
```

The application shares no network with Keycloak: it reaches it by its public address, the same as the browser's, otherwise the issuer differs and tokens are refused. Keycloak's database (about 40 to 80 MiB) is separate from the application's: **back it up**, passwords and second factors exist only there.

### The application's variables

```dotenv
OIDC_ENABLED=true
OIDC_AUTH_SERVER_URL=https://planning.exemple.org/auth/realms/planning
OIDC_CLIENT_ID=planning-app
OIDC_CLIENT_SECRET=<SECRET_CLIENT_48_CARACTERES>
OIDC_MCP_AUDIENCE=planning-mcp
OIDC_FORCE_HTTPS=true
ADMIN_LOCAL_SECOURS=false
```

The secret is at least 32 characters (48 here, `openssl rand -hex 24`): the application refuses to start below that. It does not check `OIDC_AUTH_SERVER_URL` itself: with `OIDC_ENABLED=true`, it is provider discovery, retried for `OIDC_CONNECTION_DELAY`, that fails if the address is empty or wrong. With OIDC off, write only `OIDC_ENABLED=false`.

### The reverse proxy

The **public** addresses, with no proxy authentication or geo-filtering (hosted MCP clients call from abroad, and the application queries discovery at startup): `/auth/realms/planning/*` (discovery, JWKS, authorization, token, logout, dynamic registration) and `/auth/resources/*` (CSS and JavaScript of the sign-in page). **Never public** (behind the proxy's authentication, a VPN, or closed): `/auth/admin/*`, `/auth/realms/master/*` and the rest of `/auth`. Port 9000 is never published. Everything outside `/auth` goes to the application, including `/.well-known/oauth-protected-resource`, through which an assistant discovers where to open its sign-in.

With nginx, `keycloak_proxy.conf` forwards the original host and scheme:

```nginx
location ^~ /auth/realms/planning/ { proxy_pass http://keycloak:8080; include keycloak_proxy.conf; }
location ^~ /auth/resources/       { proxy_pass http://keycloak:8080; include keycloak_proxy.conf; }
location ^~ /auth/admin/ {
    allow 192.0.2.0/24;   # administration network
    deny all;
    proxy_pass http://keycloak:8080; include keycloak_proxy.conf;
}
location ^~ /auth/realms/master/ {
    allow 192.0.2.0/24;
    deny all;
    proxy_pass http://keycloak:8080; include keycloak_proxy.conf;
}
location ^~ /auth/ { return 404; }
location / { proxy_pass http://planning-app:8080; include keycloak_proxy.conf; }

# keycloak_proxy.conf
proxy_set_header Host              $host;
proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host  $host;
proxy_set_header X-Forwarded-Port  $server_port;
proxy_buffer_size 16k;           # Keycloak headers are sometimes large
proxy_buffers 8 16k;
```

With Caddy, the same split fits in one block:

```caddy
planning.exemple.org {
    @kc_public path /auth/realms/planning/* /auth/resources/*
    handle @kc_public { reverse_proxy keycloak:8080 }
    @kc_admin {
        path /auth/admin/* /auth/realms/master/*
        remote_ip 192.0.2.0/24
    }
    handle @kc_admin { reverse_proxy keycloak:8080 }
    handle /auth/* { respond 404 }
    handle { reverse_proxy planning-app:8080 }
}
```

### Checks after deployment

To verify before announcing the sign-in (the last ones were observed on the real deployment, once the trusted hosts were set):

- public discovery (`/auth/realms/planning/.well-known/openid-configuration`) answers 200, with the exact issuer;
- the console and the `master` realm answer 401 outside the administration network;
- Keycloak refuses a foreign `redirect_uri` with 400;
- anonymous registration answers 403 while the trusted-hosts list is empty, and 201 for redirects on the three domains;
- the client so created carries `planning-mcp-audience` in its default scopes (so `aud=planning-mcp`), and consent is required;
- 403 for an out-of-list URI, for a good URI accompanied by an out-of-list one, for `claude.ai.evil.example` and for an `offline_access` request;
- 20 anonymous clients at most.

## Later: a directory, then an ADFS

The provider can change without touching the application's accounts, as long as the addresses stay the same:

- **Federate an AD or LDAP directory** in Keycloak (**User federation**): the issuer does not change. Check that each user's address is set and marked verified.
- **Switch to the client's ADFS**: the issuer changes, so [Change the provider's URL](oidc.md#changer-lurl-du-fournisseur) applies. An ADFS never sends `email_verified`: `OIDC_REQUIRE_EMAIL_VERIFIED=false` for it, never for a provider where anyone registers an address ([the variables](oidc.md#renseigner-les-variables)).
