Dev

Verifying OIDC Back-Channel Logout and JWT limits in Keycloak 26

Why RP-Initiated Logout leaves sibling app sessions alive, how Keycloak 26 Back-Channel Logout revokes them, and why stateless JWTs stay valid.

Verifying OIDC Back-Channel Logout and JWT limits in Keycloak 26

Logging out of one OIDC app leaves sibling app sessions active, and even after Back-Channel Logout clears those sessions, already-issued stateless JWT access tokens keep passing local validation until they expire. I verified RP-Initiated Logout limits, synchronous Back-Channel logout_token delivery, and Token Introspection behavior against Keycloak 26.8.2 with two live OIDC clients.

The protocol measurements below come from live HTTP runs between a Dockerized Keycloak 26.8.2 container and two lightweight Python OIDC relying parties (app-a and app-b). The Spring Security 6.4.5 configuration near the end is provided as an official API reference snippet rather than a JVM runtime run.

Why RP-Initiated Logout leaves sibling app sessions alive

As I covered in how cross-domain SSO works, an OIDC SSO deployment stores login state across three separate layers:

  1. Keycloak IdP session: the SSO session cookie (KEYCLOAK_SESSION, etc.) stored on the Keycloak domain.
  2. Each app’s local session: the server-side session cookie issued independently by app-a and app-b.
  3. Stateless access tokens (JWTs): signed bearer tokens validated directly by API servers.

Most teams start with RP-Initiated Logout. When a user clicks logout in app-a, app-a clears its own local session and redirects the browser to Keycloak’s end_session_endpoint (/protocol/openid-connect/logout). Keycloak terminates its IdP session and redirects the user back to post_logout_redirect_uri.

The gap is that app-b is never notified. Because app-b authenticates requests using its own session cookie (app_b_session), it has no idea that the IdP session ended.

To verify this directly, I registered app-a (:18481) and app-b (:18482) on Keycloak 26.8.2 without setting backchannel.logout.url. User alice signed in to app-a, entered app-b via SSO with no password prompt (sharing the same OIDC sid), and triggered RP-Initiated Logout from app-a:

1
2
3
4
5
6
7
8
[Phase 1] App A login OK: user=alice oidc_sid=<MASKED_SID_1>
[Phase 1] App B SSO login OK (no password): user=alice oidc_sid=<MASKED_SID_1>
[Phase 1] Before logout: App A /protected=200, App B /protected=200
[Phase 1] App A RP-Initiated Logout completed -> http://localhost:18481/logged-out (200)
[Phase 1] After App A logout:
  - App A /protected: 401
  - App B /protected: 200 (LOCAL SESSION STILL ALIVE!)
  - Keycloak IdP SSO alive: False (login form required: True)

app-a /protected immediately returned 401, and a fresh login attempt on Keycloak presented the password form (kc-form-login). Yet calling app-b /protected with the existing cookie still returned 200 OK. That’s why wiring only RP-Initiated Logout—as in a standalone app setup—feels like half-working Single Logout once you add a second application.

Comparing the three OIDC logout specs

OpenID Foundation defines two propagation specs on top of RP-Initiated Logout: Front-Channel Logout and Back-Channel Logout.

AspectRP-Initiated Logout 1.0Front-Channel Logout 1.0Back-Channel Logout 1.0
Delivery pathBrowser redirect to IdPHidden <iframe> per RP in IdP HTMLDirect server-to-server HTTP POST from IdP to each RP
Sessions clearedInitiating RP + IdP SSO sessionRPs whose cookies the browser sendsRP sessions matching sid / sub in logout_token
Network requirementBrowser reaches IdP and RPsBrowser reaches IdP and RPsIdP must reach each RP’s logout endpoint directly
Third-party cookie impactNoneSevere (SameSite, Safari ITP, third-party cookie blocks)None (bypasses the browser)
RP implementation costLow (redirect to end_session)Low (clear cookie on GET)Medium (logout_token validation + sid-to-session store)

Keycloak 26.8.2 advertises both mechanisms in its Discovery document (.well-known/openid-configuration):

1
2
3
4
5
6
7
8
{
  "issuer": "http://localhost:18480/realms/demo-realm",
  "end_session_endpoint": "http://localhost:18480/realms/demo-realm/protocol/openid-connect/logout",
  "backchannel_logout_supported": true,
  "backchannel_logout_session_supported": true,
  "frontchannel_logout_supported": true,
  "introspection_endpoint": "http://localhost:18480/realms/demo-realm/protocol/openid-connect/token/introspect"
}

Front-Channel Logout asks the IdP to render hidden <iframe> tags pointing to each RP’s logout URL so the browser sends cookies and clears local sessions. Under the OIDC Front-Channel Logout 1.0 spec and current browser privacy defaults (SameSite=Lax, Safari ITP, and third-party cookie blocking), cross-site <iframe> requests routinely drop session cookies, causing logouts to fail silently. I didn’t run a browser-by-browser cookie-blocking matrix in this lab; this limitation comes from the specification and browser cookie policies.

Back-Channel Logout avoids the browser altogether, but it isn’t the right fit in every architecture. Avoid or supplement it in three cases:

  • The IdP can’t reach the RP over the network: a cloud IdP calling an internal app behind a firewall, or local dev hosts without an inbound route, will fail to deliver the POST.
  • Pure browser SPAs (Public Clients): SPAs have no server-side session store to receive an IdP POST.
  • Stateless API resource servers: an API that only checks JWT signatures has no local session keyed by sid to evict.

Configuring and verifying Back-Channel Logout in Keycloak 26

For server-rendered or BFF-backed web apps, Back-Channel Logout propagates logout directly between Keycloak and each RP:

sequenceDiagram
    participant B as Browser
    participant A as App A
    participant KC as Keycloak 26
    participant RP as App B

    B->>A: Request logout
    A->>A: Clear local session
    A->>B: Redirect to IdP
    B->>KC: end_session request
    KC->>RP: POST logout_token
    RP->>RP: Verify and drop sid
    RP-->>KC: 200 OK
    KC-->>B: post_logout redirect

1. Keycloak client configuration

On the app-b client, set backchannel.logout.url and backchannel.logout.session.required. I also added an oidc-audience-mapper for the Token Introspection test in the next section. Because Keycloak runs inside Docker while app-b listens on the host at :18482, the container uses --add-host=host.docker.internal:host-gateway and targets host.docker.internal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
  "clientId": "app-b",
  "protocol": "openid-connect",
  "publicClient": false,
  "standardFlowEnabled": true,
  "redirectUris": ["http://localhost:18482/*"],
  "attributes": {
    "post.logout.redirect.uris": "http://localhost:18482/*",
    "pkce.code.challenge.method": "S256",
    "backchannel.logout.url": "http://host.docker.internal:18482/backchannel-logout",
    "backchannel.logout.session.required": "true",
    "backchannel.logout.revoke.offline.tokens": "false"
  },
  "protocolMappers": [
    {
      "name": "app-b-audience",
      "protocol": "openid-connect",
      "protocolMapper": "oidc-audience-mapper",
      "config": {
        "included.client.audience": "app-b",
        "id.token.claim": "false",
        "access.token.claim": "true",
        "introspection.token.claim": "true"
      }
    }
  ]
}

When mounting a realm JSON for --import-realm in Keycloak 26, the file under /opt/keycloak/data/import/ must follow <realm-name>-realm.json (for example, demo-realm-realm.json). Naming it demo-realm.json fails startup with File name / realm name mismatch.

2. Inspecting and validating logout_token

Keycloak sends an application/x-www-form-urlencoded POST containing logout_token=<JWT>. Here is the decoded token captured from Keycloak 26.8.2:

1
2
3
4
5
{
  "alg": "RS256",
  "typ": "logout+jwt",
  "kid": "<MASKED_KID>"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "exp": 1796316859,
  "iat": 1796316739,
  "jti": "<MASKED_JTI>",
  "iss": "http://localhost:18480/realms/demo-realm",
  "aud": "app-b",
  "sub": "<MASKED_SUB>",
  "typ": "Logout",
  "sid": "<MASKED_SID_2>",
  "events": {
    "http://schemas.openid.net/event/backchannel-logout": {}
  }
}

OIDC Back-Channel Logout 1.0 Section 2.4 requires strict validation so a logout_token can never be confused with an ID Token. In particular, nonce must be absent, events must contain http://schemas.openid.net/event/backchannel-logout as an object, and either sid or sub must be present. Notice also the RFC 8417 header typ: "logout+jwt" and the short 120-second lifetime (exp - iat).

Here is the core verification and session-eviction logic from app-b (Python 3.14, PyJWT 2.15.1):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# app-b: POST /backchannel-logout (application/x-www-form-urlencoded)
signing_key = jwks_client.get_signing_key_from_jwt(logout_token)
claims = jwt.decode(
    logout_token,
    signing_key.key,
    algorithms=["RS256"],
    issuer=ISSUER,
    audience=CLIENT_ID,
)

# Required checks per OIDC Back-Channel Logout 1.0 Section 2.4
events_claim = claims.get("events")
has_bcl_event = (
    isinstance(events_claim, dict)
    and "http://schemas.openid.net/event/backchannel-logout" in events_claim
)
has_nonce = "nonce" in claims
target_sid = claims.get("sid")
target_sub = claims.get("sub")

if not has_bcl_event or has_nonce or (not target_sid and not target_sub):
    return 400, {"error": "invalid_logout_token_claims"}

# Delete matching local sessions and reply 200 OK with Cache-Control: no-store
for local_sid, sess in list(local_sessions.items()):
    if (target_sid and sess.get("sid") == target_sid) or (
        not target_sid and target_sub and sess.get("sub") == target_sub
    ):
        del local_sessions[local_sid]

3. Observing synchronous propagation

After enabling Back-Channel Logout on app-b, I logged in fresh to both apps and triggered logout from app-a. The millisecond timestamps in app-b’s log show the exact sequence:

1
2
3
4
5
6
7
01:52:19,228 [app-b] INFO Login complete: user=alice sub=<MASKED_SUB> oidc_sid=<MASKED_SID_2> local_session=<MASKED_LOCAL_SID>
01:52:19,230 [app-b] INFO GET /protected -> 200 OK (user=alice, oidc_sid=<MASKED_SID_2>)
01:52:19,232 [app-b] INFO GET /api/me (stateless JWT) -> 200 OK (sub=<MASKED_SUB>, exp=1796317039)
01:52:19,290 [app-b] INFO Back-Channel Logout VERIFIED & PROCESSED: jti=<MASKED_JTI> sid=<MASKED_SID_2> sub=<MASKED_SUB> removed_sessions=1
01:52:19,291 [app-b] INFO HTTP 127.0.0.1 - "POST /backchannel-logout HTTP/1.1" 200 -
01:52:19,306 [app-b] INFO GET /protected -> 401 Unauthorized (cookie=<MASKED_LOCAL_SID>)
01:52:19,309 [app-b] INFO GET /api/me (stateless JWT) -> 200 OK (sub=<MASKED_SUB>, exp=1796317039)

Two details stand out. First, app-a finished GET /logged-out at 01:52:19,302—meaning Keycloak waited for app-b’s POST /backchannel-logout (01:52:19,290 → 200 OK at 01:52:19,291) to finish before redirecting the browser to post_logout_redirect_uri. At 01:52:19,306, the old app-b session cookie immediately hit 401 Unauthorized.

Second, 3 milliseconds later (01:52:19,309), GET /api/me (stateless JWT) still returned 200 OK.

Stateless JWTs after logout vs. Token Introspection

Back-Channel Logout cleared app-b’s cookie session, yet /api/me kept accepting the access token issued before logout. A stateless resource server validates only the cached JWKS RS256 signature along with iss, aud=app-b, and exp. Until accessTokenLifespan (300 seconds in this lab) runs out, the JWT remains cryptographically valid even though Keycloak already deleted the session behind it.

Querying Keycloak’s /protocol/openid-connect/token/introspect endpoint with the exact same token tells a different story:

1
2
3
4
5
6
7
[Phase 2] Before logout:
  /protected=200, /api/me(JWT)=200,
  introspect=(200) {'active': True, 'aud': 'app-b', 'sid': '<MASKED_SID_2>', 'exp': 1796317039, ...}

[Phase 2] Immediately after Back-Channel Logout:
  - Stateless JWT local JWKS (/api/me): 200 {'app': 'app-b', 'auth_mode': 'stateless_jwt_jwks', 'verified': True, 'sub': '<MASKED_SUB>', 'preferred_username': 'alice', 'sid': '<MASKED_SID_2>', 'exp': 1796317039}
  - Keycloak Token Introspection: HTTP 200 {'active': False}

Keycloak checks the token’s sid against its active session store and immediately returns {"active": false}.

Pitfall: missing aud makes Introspection return active: false even before logout

On my first run without oidc-audience-mapper, calling /token/introspect as confidential client app-b for a token issued to app-b (azp: "app-b") returned {"active": false} before logging out. Keycloak logged INTROSPECT_TOKEN_ERROR ... reason="Client 'app-b' is not in the token audience". By default, Keycloak sets aud to "account", so you must add an oidc-audience-mapper for the introspecting client ID.

Pick a mitigation strategy based on your revocation latency and traffic profile:

StrategyInstant revocationIdP load / latencyBest fit
Short access token TTL (1–5 min)No (survives until exp)LowGeneral APIs where a brief grace window is acceptable
Token Introspection (RFC 7662)YesHigh (IdP round-trip per call)Low-volume, high-sensitivity endpoints (billing, admin changes)
Shared revocation state (Redis blacklist / Token Version)YesMedium (local Redis lookup)High-traffic APIs that still need immediate revocation

If you need Redis-backed instant revocation for stateless APIs, see my earlier note on stateless JWT revocation with Redis.

Spring Security 6 reference setup and production pitfalls

In Spring Boot applications, you don’t need to write a custom logout_token parser. Spring Security 6.2+ ships with built-in Back-Channel Logout support via OidcBackChannelLogoutFilter. Below is the official API reference configuration for Spring Security 6.4.5 (Spring Boot 3.4.5). As noted at the top, I ran the protocol measurements with the Python RPs above and did not execute this JVM snippet separately.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// SecurityConfig.java (Spring Security 6.4.5 official API reference)
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/logged-out").permitAll()
            .anyRequest().authenticated()
        )
        .oauth2Login(Customizer.withDefaults())
        .oidcLogout(logout -> logout
            .backChannel(Customizer.withDefaults())
        );
    return http.build();
}

@Bean
public HttpSessionEventPublisher sessionEventPublisher() {
    // Required so Spring Security tracks HttpSession lifecycle against OIDC sid
    return new HttpSessionEventPublisher();
}

By default, Spring Security listens on /logout/connect/back-channel/{registrationId}. If your client registration ID in application.yml is keycloak, set Keycloak’s Backchannel logout URL to http://<app-b-host>/logout/connect/back-channel/keycloak. For combining OAuth2 Login, Resource Server, and Keycloak role mapping in the same app, see Spring Security 6 and Keycloak 26 OIDC role mapping.

Watch out for three production edge cases before rolling this out:

  1. Multi-instance session registries: Spring Security defaults to InMemoryOidcSessionRegistry. Behind a load balancer with multiple app instances, Keycloak’s POST can land on a different node than the one holding the user’s session. Back both HTTP sessions and OidcSessionRegistry with a shared store such as Redis.
  2. Synchronous latency and firewall rules: Because Keycloak invokes each RP’s Back-Channel endpoint synchronously before redirecting the browser, one slow or unreachable RP delays logout for everyone. Keep the handler fast, return 200 OK with Cache-Control: no-store, and allow IdP-to-RP traffic through internal firewalls.
  3. Secure cookie behavior in non-browser tests: Keycloak 26.8.2 sets Secure; SameSite=None on login cookies even in start-dev. Browsers treat http://localhost as a secure context and send those cookies, whereas HTTP clients like curl or Python requests drop Secure cookies over plain http:// unless configured otherwise.

Checklist and references

Run through these four checks before shipping OIDC Single Logout to production:

  • Account for all three session layers: Don’t rely on RP-Initiated Logout alone when multiple apps share SSO; enable Back-Channel Logout for sibling web apps.
  • Verify IdP-to-RP connectivity: Confirm Keycloak can reach each backchannel.logout.url directly and receives 200 OK with Cache-Control: no-store.
  • Enforce logout_token rules: Check signature, iss, aud, the events key, and the absence of nonce, and use a shared sid-to-session store across instances.
  • Plan for stateless JWTs: Decide upfront between short TTLs, Token Introspection (with oidc-audience-mapper), or Redis-backed revocation.
OpenID Connect Back-Channel Logout 1.0 incorporating errata set 1
Keycloak is a single sign on solution for web apps and RESTful web services. The goal of Keycloak is to make security simple so that it is easy for application developers to secure the apps and services they have deployed in their organization. Security features that developers normally have to write for themselves are provided out of the box and are easily tailorable to the individual requirements of your organization. Keycloak provides customizable user interfaces for login, registration, administration, and account management. You can also use Keycloak as an integration platform to hook it into existing LDAP and Active Directory servers. You can also delegate authentication to third party identity providers like Facebook and Google.
To perform a local logout, no special OIDC configuration is needed. Spring Security automatically stands up a local logout endpoint, which you can configure through the logout() DSL.
This post is licensed under CC BY 4.0 by the author.