Skip to main content

Keycloak and oauth2-proxy: Secure an App with a Gateway

An authenticating gateway is a reverse proxy that completes the OIDC flow with Keycloak on behalf of an application that cannot do it itself, then passes the request upstream with the user's identity in a header. To put one in front of an app with oauth2-proxy:

  1. Create a confidential client in Keycloak whose redirect URI is https://<public-host>/oauth2/callback.
  2. Run oauth2-proxy with --provider=keycloak-oidc and --oidc-issuer-url=https://<keycloak>/realms/<realm>, pointing --upstream at the app.
  3. Restrict who gets in with --allowed-role, which reads Keycloak realm and client roles.
  4. Make the app reachable only through the proxy, or the identity headers mean nothing.
  5. Forward the access token (--pass-access-token) so the app can verify it independently.
  6. Send logout through Keycloak's end_session_endpoint, not just the proxy's cookie.

That is the whole shape. The rest of this page is the three deployment layouts, what the app actually receives, and the four ways this gets built insecurely.

Tested against

Keycloak 26.8.2, oauth2-proxy v7.15.6, nginx 1.29.8, Traefik v3.6.25, and traefik/whoami v1.11 as the upstream application, all on one Linux host on 2026-11-30. Every command, header dump, error string and status code below is copied from that run.

Which problem this page solves​

Three different things get called "Keycloak and a reverse proxy", and they are not related:

You wantThat is
Keycloak itself behind nginx or Traefik, getting X-Forwarded-* and hostname righta Keycloak server setting — see the official reverse proxy guide
Your app to integrate a Keycloak library and handle its own loginSecuring applications, or the framework tutorials
Your app to be protected by a proxy that logs the user in for itthis page

The third case is what you reach for when the application cannot speak OIDC at all: a Prometheus or Grafana-style dashboard, an internal admin tool, a vendor appliance, a static site, something written in 2009. Keycloak has no proxy of its own — it is an identity provider and nothing else — so the gateway is a separate process you run.

What you'll build​

One Keycloak realm and three working layouts in front of the same application: oauth2-proxy standalone, nginx auth_request, and Traefik ForwardAuth. Then the authorization rules, the header-spoofing problem, and a verification checklist.

Step 1: a realm, a confidential client, and two users​

docker run -d --name kc --memory 1536m -p 8080:8080 \
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:26.8.2 start-dev --hostname http://localhost:8080

Pinning --hostname matters more than it looks; see the first failure mode below.

K="docker exec kc /opt/keycloak/bin/kcadm.sh"
$K config credentials --server http://localhost:8080 \
--realm master --user admin --password admin

$K create realms -s realm=demo -s enabled=true
$K create roles -r demo -s name=app-user

# the gateway is a confidential client: it holds a secret and runs server-side
$K create clients -r demo -s clientId=gateway -s publicClient=false \
-s secret=gateway-secret -s standardFlowEnabled=true \
-s 'redirectUris=["http://localhost:4180/oauth2/callback"]'

# alice may in, bob may not
$K create users -r demo -s username=alice -s enabled=true \
-s email=alice@example.com -s emailVerified=true \
-s firstName=Alice -s lastName=Example
$K set-password -r demo --username alice --new-password s3cret
$K add-roles -r demo --uusername alice --rolename app-user

$K create users -r demo -s username=bob -s enabled=true \
-s email=bob@example.com -s emailVerified=true \
-s firstName=Bob -s lastName=Example
$K set-password -r demo --username bob --new-password s3cret

A gateway is always a confidential client: it runs on a server, it keeps a secret, and it uses the authorization code flow. Never a public one.

Stand up something to protect — anything that prints the request headers will do:

docker run -d --name app --network host traefik/whoami:v1.11 --port 8000

Step 2: oauth2-proxy standalone, in front of the app​

The simplest layout: the proxy is the entry point, and the app is its upstream.

COOKIE_SECRET=$(python3 -c \
"import secrets,base64;print(base64.urlsafe_b64encode(secrets.token_bytes(32)).decode())")

docker run -d --name o2p --network host \
quay.io/oauth2-proxy/oauth2-proxy:v7.15.6 \
--provider=keycloak-oidc \
--oidc-issuer-url=http://localhost:8080/realms/demo \
--client-id=gateway \
--client-secret=gateway-secret \
--redirect-url=http://localhost:4180/oauth2/callback \
--upstream=http://127.0.0.1:8000/ \
--http-address=127.0.0.1:4180 \
--cookie-secret="$COOKIE_SECRET" \
--cookie-secure=false \
--email-domain='*' \
--skip-provider-button=true \
--allowed-role=app-user \
--set-xauthrequest=true \
--pass-access-token=true \
--code-challenge-method=S256

--cookie-secure=false is for this lab only; over HTTPS, drop it. Use keycloak-oidc, not the older keycloak provider, which is deprecated. --code-challenge-method=S256 turns on PKCE; without it oauth2-proxy logs Warning: Your provider supports PKCE methods and proceeds anyway.

Sign in as alice, and the application receives:

X-Forwarded-User: 9f11a95d-47a0-4a7e-9c60-419443284e43
X-Forwarded-Email: alice@example.com
X-Forwarded-Preferred-Username: alice
X-Forwarded-Groups: role:offline_access,role:default-roles-demo,role:uma_authorization,
role:app-user,role:account:manage-account,...
X-Forwarded-Access-Token: eyJhbGciOiJSUzI1NiIs...

Three things are worth stopping on:

  • X-Forwarded-User is the sub UUID, not the username. An app that greets the user with it will print a GUID. The username is X-Forwarded-Preferred-Username.
  • X-Forwarded-Groups carries Keycloak roles, prefixed role: — realm roles as role:<name>, client roles as role:<client>:<name>. Real Keycloak groups only appear here if you add a group-membership mapper and a groups claim.
  • The default roles Keycloak grants every account (offline_access, uma_authorization, default-roles-<realm>, the three account client roles) are in that list too, so "has a role" is a useless test. Name the one you mean.

Step 3: authorization, and what rejection looks like​

--allowed-role=app-user is already set, so sign in as bob:

403 Forbidden — You do not have permission to access this resource.

and in the proxy log:

[AuthFailure] Invalid authentication via OAuth2: unauthorized

Note what happened: bob authenticated successfully at Keycloak and was then refused at the gateway. 401 means "who are you", 403 means "not you". For client roles the syntax is --allowed-role=<clientId>:<roleName>. See roles, composite roles, and groups for which of those you should be modelling.

For per-route rules, the /oauth2/auth endpoint takes a query parameter, which the two layouts below can vary per location:

curl -o /dev/null -w "%{http_code}\n" -b cookies \
"http://localhost:4180/oauth2/auth?allowed_groups=role:app-user" # 202
curl -o /dev/null -w "%{http_code}\n" -b cookies \
"http://localhost:4180/oauth2/auth?allowed_groups=role:billing" # 403

Step 4: layout two — nginx auth_request​

Here nginx is the entry point and oauth2-proxy answers a subrequest for every request.

server {
listen 8081;
server_name localhost;

# oauth2-proxy's own endpoints: sign_in, callback, sign_out, static assets
location /oauth2/ {
proxy_pass http://127.0.0.1:4180;
proxy_set_header Host $host:8081;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Auth-Request-Redirect $scheme://$host:8081$request_uri;

# a Keycloak session cookie is ~3.8 KB; the default 4k buffer 502s on the callback
proxy_buffer_size 16k;
proxy_buffers 4 16k;
proxy_busy_buffers_size 16k;
}

location = /oauth2/auth {
internal;
proxy_pass http://127.0.0.1:4180;
proxy_set_header Host $host:8081;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Uri $request_uri;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_buffer_size 16k;
proxy_buffers 4 16k;
proxy_busy_buffers_size 16k;
}

location / {
auth_request /oauth2/auth;
error_page 401 = @oauth2_signin;

auth_request_set $user $upstream_http_x_auth_request_user;
auth_request_set $email $upstream_http_x_auth_request_email;
auth_request_set $uname $upstream_http_x_auth_request_preferred_username;
auth_request_set $groups $upstream_http_x_auth_request_groups;
auth_request_set $token $upstream_http_x_auth_request_access_token;

proxy_set_header X-Forwarded-User $user;
proxy_set_header X-Forwarded-Email $email;
proxy_set_header X-Forwarded-Preferred-Username $uname;
proxy_set_header X-Forwarded-Groups $groups;
proxy_set_header Authorization "Bearer $token";

# anything nginx does not set here is whatever the client sent — see Security below
proxy_set_header X-Auth-Request-User "";
proxy_set_header X-Auth-Request-Email "";
proxy_set_header X-Auth-Request-Groups "";
proxy_set_header X-Auth-Request-Access-Token "";
proxy_set_header X-Forwarded-Access-Token "";

proxy_pass http://127.0.0.1:8000/;
}

location @oauth2_signin {
internal;
return 302 /oauth2/sign_in?rd=$scheme://$host:8081$request_uri;
}
}

Run oauth2-proxy with --upstream='static://202', --reverse-proxy=true, --whitelist-domain=localhost:8081 and --redirect-url=http://localhost:8081/oauth2/callback. It no longer proxies traffic; it only answers /oauth2/*.

The proxy buffers are not optional. Without them the login succeeds at Keycloak, oauth2-proxy logs [AuthSuccess], and nginx still returns 502 on the callback:

[error] upstream sent too big header while reading response header from upstream,
request: "GET /oauth2/callback?state=...&code=..."

The _oauth2_proxy cookie carrying a Keycloak session measured 3,780 bytes in this lab — the Set-Cookie header alone overruns nginx's default 4k response-header buffer. This is the single most common "it works until it doesn't" failure of this layout, and the error names the buffer rather than the cookie, so nobody connects the two.

Step 5: layout three — Traefik ForwardAuth​

traefik.yml:

entryPoints:
web:
address: ":8082"
providers:
file:
filename: /etc/traefik/dynamic.yml

dynamic.yml:

http:
routers:
oauth2: # must NOT be behind the middleware
rule: "PathPrefix(`/oauth2/`)"
priority: 100
entryPoints: [web]
service: oauth2-proxy
app:
rule: "PathPrefix(`/`)"
priority: 1
entryPoints: [web]
service: whoami
middlewares: [strip-identity, forward-auth-errors, forward-auth]

middlewares:
# ForwardAuth only replaces the headers named in authResponseHeaders;
# every other identity header arrives from the client untouched
strip-identity:
headers:
customRequestHeaders:
X-Forwarded-User: ""
X-Forwarded-Email: ""
X-Forwarded-Groups: ""
X-Forwarded-Preferred-Username: ""
X-Forwarded-Access-Token: ""

# without statusRewrites the browser is handed a 401 containing a link, not a redirect
forward-auth-errors:
errors:
status: ["401-403"]
service: oauth2-proxy
query: "/oauth2/sign_in?rd={url}"
statusRewrites:
"401": 302

forward-auth:
forwardAuth:
address: "http://127.0.0.1:4180/oauth2/auth"
trustForwardHeader: true
authResponseHeaders:
- X-Auth-Request-User
- X-Auth-Request-Email
- X-Auth-Request-Preferred-Username
- X-Auth-Request-Groups
- X-Auth-Request-Access-Token

services:
oauth2-proxy:
loadBalancer:
servers: [{ url: "http://127.0.0.1:4180" }]
whoami:
loadBalancer:
servers: [{ url: "http://127.0.0.1:8000" }]

/oauth2/auth returns a bare 401 Unauthorized, and Traefik hands that straight to the browser. There is no automatic sign-in redirect: with only the forwardAuth middleware in place, an unauthenticated browser gets HTTP/1.1 401 Unauthorized and the body Unauthorized. The errors middleware fixes it, and statusRewrites is the part people leave out — without it the browser renders a "Found." link instead of following the redirect. With both, the same request returns 302 to http://localhost:8080/realms/demo/protocol/openid-connect/auth?....

Two smaller notes. The file provider watches the file by name, so bind-mount the directory, not the file — replacing the file's inode leaves Traefik serving the old config and your edit appears to have done nothing. And Traefik 3 logs maxResponseBodySize is not configured for every ForwardAuth middleware; set it.

Security: the four things that make this real​

1. The app's own port is the whole attack surface. Identity headers are trustworthy only because the proxy is the only way in. Reach the app directly and anything goes:

$ curl -H 'X-Forwarded-User: admin' http://127.0.0.1:8000/
X-Forwarded-User: admin

Bind the app to loopback or a private network, or put it on the proxy's network namespace. Nothing in the gateway can compensate for a reachable upstream port.

2. Strip inbound copies of every identity header. Standalone oauth2-proxy overwrites all of them — a request carrying X-Forwarded-User: attacker arrives upstream as the real subject. The two subrequest layouts do not:

LayoutForged X-Forwarded-UserForged header you did not list
oauth2-proxy standaloneoverwrittenoverwritten
nginx auth_requestoverwritten if you proxy_set_header itpasses through
Traefik ForwardAuthoverwritten if it is in authResponseHeaderspasses through

Measured: through nginx with only four headers set, X-Forwarded-Groups: role:admin and X-Auth-Request-User: attacker both reached the application untouched. Through Traefik, a forged X-Forwarded-User: attacker reached it, because only the X-Auth-Request-* names were listed. Both configs above now clear them explicitly. Enumerate what you strip; do not enumerate what you trust.

3. Forward the access token and verify it anyway. --pass-access-token puts the token in X-Forwarded-Access-Token, and an app that validates it does not have to take the proxy's word for anything. That needs the aud claim to name the gateway client, which Keycloak does not do by default — out of the box the token's audience is account:

CID=$($K get clients -r demo -q clientId=gateway --fields id --format csv --noquotes)
$K create clients/$CID/protocol-mappers/models -r demo \
-s name=gateway-audience -s protocol=openid-connect \
-s protocolMapper=oidc-audience-mapper \
-s 'config."included.client.audience"=gateway' \
-s 'config."access.token.claim"=true'

aud becomes ["gateway","account"]. The full check order is in validating Keycloak tokens in any backend, and the claim itself in getting the aud claim right.

4. Logout is three sessions, and the proxy only ends one. /oauth2/sign_out clears _oauth2_proxy and nothing else. Measured: immediately after signing out, the next request reached the application again without a password prompt, because Keycloak's SSO session was still live. Send the user onward to the end_session_endpoint:

/oauth2/sign_out?rd=<url-encoded>
http://localhost:8080/realms/demo/protocol/openid-connect/logout
?id_token_hint={id_token}
&post_logout_redirect_uri=http://localhost:8082/

oauth2-proxy substitutes {id_token}. The Keycloak host must be in --whitelist-domain, and post.logout.redirect.uris must be set on the client, or Keycloak refuses the redirect. With that in place the next request lands on the login form. Background: OIDC logout: back-channel, front-channel, RP-initiated.

The one failure that stops it booting​

Point --oidc-issuer-url at an internal address while Keycloak publishes an external one and oauth2-proxy exits 1 before serving anything:

ERROR: Failed to initialise OAuth2 Proxy: ... oidc: issuer did not match the issuer
returned by provider, expected "http://127.0.0.1:8080/realms/demo"
got "http://localhost:8080/realms/demo"

The issuer string is compared exactly. Use the public issuer URL everywhere, and make sure the proxy can resolve it — this is why --hostname was pinned in step 1. A Keycloak left to derive its hostname from the request will tell each caller a different issuer, which hides the problem in the lab and produces it in production.

Which gateway to run​

ProjectStarsLatestNotes
oauth2-proxy~15,400v7.15.6 (2026-11-05)Generic OIDC with a dedicated keycloak-oidc provider. The default choice.
pomerium~5,100v0.34.2 (2026-11-25)Policy engine as well as a proxy; worth it if you need per-route policy, heavier if you don't.
gogatekeeper~3205.1.0 (2026-11-18)Keycloak-specific, actively released, small community. The continuation of the old Keycloak Gatekeeper lineage.
keycloak/keycloak-gatekeeper——Dead. Redirects to louketo/louketo-proxy, which the Keycloak project sunset in 2020 and archived on 2023-08-30. Do not start here.

Counts and dates read from the GitHub API on 2026-11-30. If you are following a tutorial that tells you to docker pull keycloak/keycloak-gatekeeper, it predates the sunset.

When you should not use a gateway​

  • Authorization is all-or-nothing. The gateway knows the URL and the user's roles. It cannot express "this user may edit this document". Anything per-object still belongs in the app.
  • Logout is genuinely awkward, as above — three sessions, and only a deliberate end_session_endpoint round trip ends them together.
  • Non-browser clients need a second path. A cookie-based gateway has nowhere to put a login prompt for curl or a CI job. Use --skip-jwt-bearer-tokens so verified bearer tokens pass straight through, and --api-route so those paths get a 401 instead of a redirect.
  • WebSockets and long-lived connections authenticate once, at upgrade, and then run past the token's expiry with nothing re-checking.
  • Refresh happens at the proxy, so the token the app sees is refreshed without the app noticing, and app-side session timeouts stop meaning what you think. The session lifetime that matters is Keycloak's.
  • If the app can speak OIDC, let it. A library in the app gives you per-object authorization, a real logout, and one fewer process. The gateway exists for applications that cannot.

Verify you got it right​

  1. Unauthenticated request to the public URL → redirect to Keycloak, not a 401 page.
  2. Sign in as alice → the app renders, and X-Forwarded-Preferred-Username is alice.
  3. Sign in as bob → 403 at the gateway, not a Keycloak error.
  4. curl -H 'X-Forwarded-User: attacker' at the public URL with a valid session → the app still sees alice's subject.
  5. curl the app's own port directly from another host → connection refused.
  6. Decode X-Forwarded-Access-Token → aud contains the gateway client, iss is the public issuer URL.
  7. Sign out via end_session_endpoint, then reload → the Keycloak login form.

A deployment that passes 1–3 works. One that also passes 4–7 is the one you can leave running.

Next steps​