<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohammedsiraj on Medium]]></title>
        <description><![CDATA[Stories by Mohammedsiraj on Medium]]></description>
        <link>https://medium.com/@mohammedsiraj2013?source=rss-e6ac29a21ff7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QdA1sqL8VLATChYW.jpg</url>
            <title>Stories by Mohammedsiraj on Medium</title>
            <link>https://medium.com/@mohammedsiraj2013?source=rss-e6ac29a21ff7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:08:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohammedsiraj2013/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Refresh Tokens and Session Timeouts in Keycloak: Why a 400 Isn’t Always a Bug]]></title>
            <link>https://medium.com/@mohammedsiraj2013/refresh-tokens-and-session-timeouts-in-keycloak-why-a-400-isnt-always-a-bug-d7cf3c5b5f7f?source=rss-e6ac29a21ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7cf3c5b5f7f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[keyclock]]></category>
            <category><![CDATA[sso]]></category>
            <dc:creator><![CDATA[Mohammedsiraj]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 05:37:19 GMT</pubDate>
            <atom:updated>2026-09-14T05:37:19.965Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A guide for developers maintaining Keycloak-based authentication — how access tokens expire, how the refresh flow works, and why Keycloak sometimes refuses to renew a session that looks perfectly fine from the frontend.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oaslhd-5i2zCnrVHqbjs6Q.png" /></figure><h3>Why this article exists</h3><p>A request to Keycloak’s token endpoint occasionally comes back with 400 Bad Request. The instinctive read is &quot;the refresh API is broken.&quot; It usually isn&#39;t. Keycloak is intentionally refusing to renew a session that has expired, gone idle, been revoked, or hit its maximum lifetime — and none of those are bugs.</p><p>This guide covers the full picture: what access and refresh tokens actually are, how the refresh flow works end to end, the two session settings that decide whether a refresh is even allowed, and the frontend patterns — and anti-patterns — around handling all of it.</p><h3>1. Two tokens, two very different jobs</h3><p>Keycloak hands your app three things after login: an <strong>access token</strong>, a <strong>refresh token</strong>, and an <strong>ID token</strong>. The distinction that matters day to day is between the first two.</p><p>TokenPurposeLifetimeAccess tokenSent on every API request, to prove who’s callingShort — minutesRefresh tokenSent only to Keycloak, to get a new access tokenLonger — often 30+ minutesOffline tokenAccess that survives beyond the normal SSO sessionVery long, policy-based</p><p>A simple way to keep them straight: the access token is a temporary ID badge — it’s what you flash at every door. The refresh token is the paperwork that gets you a replacement badge when the old one expires. It never gets flashed at a door itself, and it should never be sent to your own backend APIs — only to Keycloak’s token endpoint.</p><h3>2. The normal flow</h3><p>Login returns all three tokens. From then on, the frontend attaches the access token to every request:</p><pre>GET /api/products<br>Authorization: Bearer eyJ...</pre><p>Access tokens are deliberately short-lived — 5 to 15 minutes is typical. Say the lifetime is 5 minutes and the user logs in at 09:00. By 09:05, the access token is expired, and the next request comes back 401 Unauthorized.</p><p>That 401 does not mean the user is logged out. It means the frontend needs to refresh.</p><h3>3. The refresh call itself</h3><p>The frontend calls Keycloak’s token endpoint directly, using the refresh token:</p><pre>POST /realms/{realm}/protocol/openid-connect/token<br>Content-Type: application/x-www-form-urlencoded</pre><pre>grant_type=refresh_token<br>client_id=&lt;client-id&gt;<br>refresh_token=&lt;refresh-token&gt;</pre><p>A healthy response looks like this:</p><pre>{<br>  &quot;access_token&quot;: &quot;new-access-token&quot;,<br>  &quot;expires_in&quot;: 300,<br>  &quot;refresh_token&quot;: &quot;new-refresh-token&quot;,<br>  &quot;refresh_expires_in&quot;: 1800<br>}</pre><p>The frontend saves the new access token, retries the original request, and the user never notices any of it happened.</p><h3>4. The rule that’s easy to miss: always save the newest refresh token</h3><p>That response includes a <em>new</em> refresh token, not just a new access token. If <strong>refresh token rotation</strong> is enabled on the realm — which invalidates the previous refresh token the moment a new one is issued — continuing to use the old one will fail on the very next refresh.</p><p>javascript</p><pre>// Correct<br>saveAccessToken(response.access_token);<br>if (response.refresh_token) {<br>  saveRefreshToken(response.refresh_token);<br>}</pre><p>javascript</p><pre>// Wrong — keeps using the token that rotation just invalidated<br>const refreshToken = originalRefreshToken;</pre><p>This single line — overwriting the stored refresh token on every refresh, not just the first one — is the difference between a session that quietly renews itself for hours and one that dies on the second refresh.</p><h3>5. The two settings that actually decide whether a refresh works: Idle vs. Max</h3><p>Every Keycloak realm has, at minimum, these two session settings, and confusing them is the single most common source of “why did this session die” questions:</p><ul><li><strong>SSO Session Idle</strong> — how long a session can sit with <em>no activity</em> before Keycloak kills it. Refreshing resets this timer.</li><li><strong>SSO Session Max</strong> — a hard ceiling on the session’s total age, counted from the original login. Refreshing does <strong>not</strong> reset this timer. Nothing does.</li></ul><p>Put plainly:</p><pre>IDLE = how long since the session was last active<br>MAX  = how long since the user originally logged in</pre><p>A session with Idle = 30 minutes and Max = 16 hours behaves like this: the user can refresh every few minutes all day and the idle clock keeps resetting — but at 16 hours from login, the session ends regardless of how recently they were active. Continuous, perfectly-timed refreshes do not buy a longer session; they only keep it alive <em>within</em> the 16-hour window.</p><p>Client-level settings — Client Session Idle / Client Session Max — work the same way, scoped to one client instead of the whole realm. Both pairs matter; whichever is shorter wins.</p><p><strong>Why 16 hours, as an example:</strong> a team running an ERP for a roughly 12-hour working day might set Session Max to 12 hours of work plus a 4-hour buffer — 16 hours total — so a session survives a full shift without forcing a re-login mid-task, without staying valid indefinitely either. The number itself is a business decision, not a technical one; the important part is understanding what it actually controls.</p><p><strong>Why 30-minute idle can still surprise people:</strong> even with a generous 16-hour max, a 30-minute idle timeout means a long lunch or a long meeting can end the session early. If users are expected to step away and come back without re-authenticating, that’s a reason to revisit the idle setting — again, a business/security call, not something to quietly work around in frontend code.</p><h3>6. Why Keycloak returns 400 — and why that’s not automatically a bug</h3><p>A refresh call can fail with:</p><pre>{<br>  &quot;error&quot;: &quot;invalid_grant&quot;,<br>  &quot;error_description&quot;: &quot;Token is not active&quot;<br>}</pre><p>This can mean any of:</p><ul><li>the refresh token itself expired</li><li>the session hit its idle timeout</li><li>the session hit its max lifetime</li><li>the user (or an admin) logged the session out</li><li>the session was revoked</li><li>rotation invalidated an older token that’s still being used somewhere</li><li>two refresh calls raced and one reused a token the other had already replaced</li></ul><p>None of those are server failures. Before assuming otherwise, read error and error_description on the response — they tell you which of the above actually happened.</p><h3>7. Handling it on the frontend, correctly</h3><p>The shape that holds up:</p><pre>401 on API request<br>  → try refresh, exactly once<br>      → success: save new tokens, retry the original request<br>      → failure: clear auth state, redirect to login</pre><p>The failure mode to avoid is a refresh loop: 401 → refresh → 400 → refresh again → 400 again, indefinitely. That turns one expired session into a stream of requests hitting Keycloak, plus a UI that never resolves. A failed refresh should be terminal — clear the tokens, clear the auth state, send the user to login, and stop.</p><h3>8. Parallel requests need a single-flight refresh</h3><p>A dashboard that fires five requests at once (/products, /users, /categories...) with an expired access token gets five 401s back. If each one independently calls refresh, and rotation is enabled, the first refresh invalidates the token the other four are about to use — so four of the five refresh attempts fail with 400 invalid_grant, even though nothing was actually wrong with the session.</p><p>The fix is a mutex: the first 401 triggers the one and only refresh call; every other request in flight waits on that same call and retries once it resolves.</p><pre>if (tokenExpired) {<br>  if (!refreshInProgress) {<br>    refreshInProgress = refreshToken();<br>  }</pre><pre>  try {<br>    const tokens = await refreshInProgress;<br>    updateTokens(tokens);<br>    return retryOriginalRequest();<br>  } finally {<br>    refreshInProgress = null;<br>  }<br>}</pre><p>The mechanism can be a hand-rolled promise lock, an Axios interceptor queue, or an RTK Query baseQuery wrapper — the implementation varies, but the rule doesn&#39;t: <strong>one refresh in flight at a time</strong>, no matter how many requests are waiting on it.</p><h3>9. Settings that look related but aren’t: Login Timeout and Login Action Timeout</h3><p>Two more realm settings are easy to confuse with session lifetime, but they govern something else entirely — the login process itself, not the session that follows it:</p><ul><li><strong>Login Timeout</strong> — how long the <em>entire</em> authentication flow (credentials, MFA, any required actions) is allowed to stay open before it has to complete.</li><li><strong>Login Action Timeout</strong> — how long a single step within that flow (an OTP screen, for instance) can sit unanswered.</li></ul><p>Neither one affects how long an already-authenticated session lasts. They only matter while the user is in the middle of logging in.</p><h3>10. Offline sessions — a different tool for a different problem</h3><p>A realm can also have <strong>offline sessions</strong>, requested via scope=offline_access. These let an app get new access tokens even after the normal SSO session has fully expired — designed for &quot;log in once, stay authenticated tomorrow, and next week&quot; scenarios, not for a single working day.</p><p>For a normal business-hours session (a 12-hour shift plus a buffer, say), offline access usually isn’t needed — a well-tuned Session Max already covers the requirement, and it’s the simpler, more secure option. Reach for offline sessions only when the actual requirement is persistence across days or weeks, not within one.</p><h3>11. Debugging checklist: when refresh comes back 400</h3><p>In order:</p><ol><li>Read the actual response — error and error_description.</li><li>Check when the user logged in, relative to Session Max (both realm and client level).</li><li>Check how long the user was inactive, relative to Session Idle (both realm and client level).</li><li>Check for client-specific overrides (Clients → &lt;client&gt; → Advanced).</li><li>Check whether refresh token rotation is enabled.</li><li>Check whether multiple requests refreshed at the same time.</li><li>Check whether the frontend is actually storing the newest refresh token after each refresh, not just the first one.</li><li>Check whether the session was manually ended — by the user, or by an admin.</li></ol><h3>12. The mental model to keep</h3><p>Three layers, and the dependency runs one direction:</p><pre>Access token                   → used for normal API calls<br>Refresh token                   → used to get a new access token<br>Keycloak session (Idle + Max)   → decides whether that refresh is allowed at all</pre><p>A refresh token is never independent of the session behind it. If the session is gone — idle too long, past its max age, revoked, logged out — no refresh token will save it, and that’s the system working as designed, not a bug to route around.</p><h3>Checklist</h3><ul><li>Access token expiring is not the same as the session expiring — try a refresh before treating a 401 as a logout.</li><li>After every refresh, store the <em>new</em> refresh token, not just the new access token.</li><li>Idle and Max are different clocks: idle resets on activity, max never does.</li><li>A failed refresh is terminal — refresh once, and on failure clear auth and redirect, never loop.</li><li>Concurrent 401s share a single refresh call; don’t let five requests each trigger their own.</li><li>Login Timeout / Login Action Timeout govern the login process, not session lifetime — don’t conflate them with Idle/Max.</li><li>Offline sessions solve a multi-day persistence problem, not a single working-day one — don’t reach for them by default.</li><li>A 400 from the token endpoint is diagnostic information, not proof of a broken API — read the error body before assuming the worst.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7cf3c5b5f7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building SSO with Keycloak: What Actually Happens Between Login and Dashboard]]></title>
            <link>https://medium.com/@mohammedsiraj2013/building-sso-with-keycloak-what-actually-happens-between-login-and-dashboard-d53594325554?source=rss-e6ac29a21ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d53594325554</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[keycloak-integration]]></category>
            <category><![CDATA[sso]]></category>
            <dc:creator><![CDATA[Mohammedsiraj]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 05:44:27 GMT</pubDate>
            <atom:updated>2026-09-09T05:44:27.530Z</atom:updated>
            <content:encoded><![CDATA[<p>How SSO with Keycloak actually works — sessions, tokens, storage, refresh, and logout — for teams shipping it for real, not just reading the spec.</p><h3>Why this article exists</h3><p>Most SSO explanations stop at “one login that works across apps.” That’s accurate, but it skips the actual engineering behind it: how a session is issued, where the tokens that prove it are stored, how they get renewed, and how logout is made to work across every tab and every connected app at once.</p><p>This guide covers those decisions in order: what SSO is, how Keycloak is configured, how login works, where tokens live, how sessions refresh, and how logout is implemented correctly.</p><p>We use Keycloak as the identity provider and a Next.js + Redux frontend as the working example, since that’s what most teams are actually building on. If you’re using Auth0, Okta, or Azure AD instead, almost everything here still applies — they all follow the same OpenID Connect (OIDC) spec, just with a different admin screen.</p><p><em>All URLs, realm names, and client IDs below are fictional placeholders. Never commit real credentials or production values to source control.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzb8RTqXz6xwpYU41PpALQ.png" /></figure><h3>1. What SSO actually is (and how it gets handled)</h3><p>Here’s the whole idea, with no jargon:</p><p><strong>Single Sign-On (SSO) means: log in once, and use many apps without logging in again.</strong></p><p>The app you’re using doesn’t check your password itself. A separate system does that for you. In this guide, that system is <strong>Keycloak</strong>.</p><p>That separate system is called an <strong>Identity Provider</strong>, or <strong>IdP</strong>. Any app that trusts it — your ERP, your CRM, your internal dashboard — is called a <strong>client</strong>. The app never sees the user’s password. It only ever sees a signed token that says “yes, this person logged in,” which it can check and move on from.</p><p><strong>Before anything else, four Keycloak terms you’ll see constantly. Learn these now — everything later in the guide assumes you know them.</strong></p><ul><li><strong>Realm</strong> — a walled-off space inside Keycloak for one organization or product. Users, apps, and settings in one realm don’t mix with another realm. A company might run company-realm for internal staff apps and a separate partner-realm for outside partners; a user in one has no access to the other.</li><li><strong>Client / Client ID</strong> — every app that wants to use Keycloak for login has to be registered inside a realm as a client. The client ID is just the name Keycloak recognizes that app by — for example, erp-frontend for the ERP app.</li><li><strong>SSO Session Max</strong> — the hard ceiling on how long a login session can last, period. Once this time is up, Keycloak logs the user out and makes them sign in again, even if they’ve been actively using the app the whole time.</li><li><strong>SSO Session Idle</strong> — how long a session can sit untouched before Keycloak ends it early. If a user walks away and doesn’t come back within this window, the session dies even though Session Max hasn’t run out yet.</li></ul><p>Both settings live in Keycloak’s admin console, per realm, and they’re the reason Section 6 (silent refresh) exists at all: get Session Idle too short, and users get logged out mid-task; get Session Max too long, and a stolen laptop stays logged in far longer than security wants.</p><p><strong>Two other words that get blurred constantly, and shouldn’t be:</strong></p><ul><li><strong>Authentication</strong> — proving who you are. Keycloak’s job, full stop.</li><li><strong>Authorization</strong> — deciding what you’re allowed to do once you’re recognized. Always your app’s job. Keycloak can hand you a user’s roles, but whether those roles let this user approve a purchase order, or see another branch’s data, is a decision your backend makes — never the identity provider.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGLTlYnsmI6L2ptFyYGoUA.png" /></figure><p>A user can be fully, successfully authenticated by Keycloak and still get told “no” by your API. That’s not a bug. That’s the design working correctly.</p><p><strong>So, step by step, what actually happens?</strong></p><p>Every login — and every session refresh, and every logout — is the same basic sequence, repeated with small variations:</p><ol><li>Your app has no valid session, so it sends the browser to Keycloak instead of showing its own login form.</li><li>Keycloak checks the user’s credentials — or, if a session already exists from another app, skips straight to step 3 with nothing shown to the user.</li><li>Keycloak sends the browser back to your app with a signed, checkable proof that says who just logged in.</li><li>Your app checks that proof, works out what this user is allowed to see, and only then renders anything.</li></ol><p>Everything else in this guide is just the fine print on each of these four steps: which protocol actually does steps 1–3 (Section 3), what step 3’s “proof” is made of (Section 4), where it has to be stored so a page refresh doesn’t lose it (Section 5), how to keep it fresh in the background (Section 6), and how to tear it all down cleanly on logout (Section 7).</p><p>New to this? Read this section twice before moving on — the token handling, the Redux-vs-cookie decision, the logout bugs later in this guide are all consequences of the four steps above. Reviewing someone else’s SSO implementation? Those same four steps are the four places to check first, because that’s exactly where real implementations quietly drift from the spec.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_WjfZGabXwBwrheeRp2BA.png" /></figure><h3>2. The problem, before the protocol</h3><p>Picture an org with three internal apps — say, an ERP and an HRMS. Without SSO, you’ve got two options, and both are bad:</p><p>Each app keeps its own user table. Someone leaves the company, and offboarding means remembering to disable them in three different places. One gets missed. That’s how ex-employees keep access.</p><p>One app is bolted onto another’s login. Works fine for two apps. Falls apart the moment there’s a third.</p><p>SSO solves this by introducing a party that neither app fully owns, but both defer to: the Identity Provider. Keycloak sits in the middle, does the actual authenticating, and hands each app back proof of who just logged in.</p><p>The spec that standardizes “hand back proof of who logged in” is <strong>OpenID Connect (OIDC)</strong> — an identity layer sitting on top of OAuth 2.0. This one distinction is worth keeping in your head: OIDC isn’t something Keycloak invented, it’s a spec Keycloak (and Auth0, and Okta, and everyone else) implements the same way. That’s the whole reason this article transfers to whatever IdP you’re actually using.</p><h3>3. The login flow — what’s actually happening behind that redirect</h3><p>A browser-based SPA is what OAuth calls a <strong>public client</strong>: it ships to the user’s machine, so it can’t be trusted with a secret. The flow built for exactly this situation is <strong>Authorization Code with PKCE</strong> (Proof Key for Code Exchange) — and as of 2026, it’s the flow every browser app should be using. If you see the older implicit flow in a codebase, that’s a flag to raise in review, not copy.</p><p>&lt;image/&gt;</p><p>Two details that are easy to skim past as a junior and painful to relearn later:</p><p>The redirect isn’t cosmetic. Credentials get typed into a page served from Keycloak’s own domain — not your app’s. Your app’s code never holds the password, not in memory, not in a variable, not accidentally in a log line. It structurally can’t leak what it never touched.</p><p>The token exchange is a direct call, not a redirect. The authorization code that comes back in the URL is short-lived and single-use. The actual tokens come from a follow-up request the browser makes straight to Keycloak’s token endpoint — which is why they never end up sitting in browser history or a referrer header.</p><h3>4. Two tokens, two authorities — the mistake that costs the most</h3><p>Keycloak hands your app three tokens after login: an access token, a refresh token, and an ID token.</p><p>Here’s the design decision that separates a robust SSO implementation from a fragile one: Keycloak’s access token should not be the credential your own API trusts on every request. Keycloak knows the user authenticated. It knows nothing about your app’s roles, tenant, or permissions. That’s not its job.</p><p>The pattern that holds up is a dual-token handoff:</p><p><strong>Keycloak tokens</strong> — prove identity to Keycloak, carry the id_token_hint needed for a clean logout, and are exchanged once for your app&#39;s own token. They are never sent to your own API.</p><p><strong>App session token (backend JWT)</strong> — issued by your backend, in exchange for a valid Keycloak access token. This carries your app’s own claims (roles, branch, tenant) and is what goes on Authorization: Bearer for every real API call.</p><pre>POST /api/auth/me<br>Authorization: Bearer &lt;keycloak_access_token&gt;</pre><pre>// backend verifies the token against Keycloak&#39;s public keys,<br>// resolves the user&#39;s app-side profile, and returns:<br>{ &quot;token&quot;: &quot;&lt;app_session_jwt&gt;&quot;, &quot;user&quot;: { ... }, &quot;permissions&quot;: [...] }</pre><p>Why bother with two tokens instead of just trusting Keycloak’s directly? Because the day you swap identity providers, or bolt a second app onto the same realm, this one exchange endpoint is the only thing that changes. Every other route in your app is already speaking your own token format and doesn’t care where identity came from.</p><h3>5. Where the tokens actually live — Redux vs. cookies</h3><p>This is where most SSO bugs are quietly born, because “in memory” and “persisted” look identical until someone hits reload.</p><p>A page reload wipes Redux clean. It does not wipe a cookie. So the rule is simple, even if it’s easy to violate without noticing: anything you need to recover a session without re-prompting for a password has to live in a cookie (or other persistent storage) — Redux is a cache, never the source of truth.</p><p>A concrete way this bites teams: tokens get stored only in Redux. Something totally unrelated — a route change, a hot reload, a browser quirk — triggers a full page refresh. Redux resets. The logout button then tries to build Keycloak’s end-session URL, but the id_token_hint it needs is gone, because that only ever lived in the store that just reset. Keycloak, unable to identify which session to end, falls back to a confirmation page — &quot;Do you want to log out?&quot; — instead of just logging out. Nothing crashed. The code was even spec-compliant. It&#39;s just that the wrong thing was treated as the source of truth.</p><p>The fix generalizes past this one bug: whatever store your app resets on reload — Redux, a global context, an in-memory cache — is never a valid single source of truth for session data. It’s an optimization layer over a persisted value, and your read path should always fall back to that persisted value.</p><h3>6. Silent refresh — staying logged in without anyone noticing</h3><p>If your access token dies every 10 minutes, “re-login every 10 minutes” is not an acceptable UX. Silent refresh trades the long-lived refresh token for a fresh access token in the background — no UI, no redirect, no interruption.</p><p>There are exactly two moments this should fire:</p><p><strong>Proactive</strong> — a timer, running at or under the access token’s lifespan (commonly every 5 minutes), that refreshes ahead of expiry.</p><p><strong>Reactive</strong> — any API call that comes back 401. Refresh once, then replay the original request. This catches what the timer misses — a laptop that slept through a few ticks, for instance.</p><p>The detail that separates a robust implementation from a flaky one: make the refresh single-flight. If ten API calls fail with 401 in the same second, they need to share one refresh call, not fire ten independently.</p><p>javascript</p><pre>// src/utils/silentTokenRefresh.js<br>let refreshPromise = null;</pre><pre>export function silentRefreshBackendToken() {<br>  if (!refreshPromise) {<br>    refreshPromise = performRefresh()<br>      .catch((error) =&gt; {<br>        if (error instanceof SessionExpiredError) {<br>          forceSsoLogout();<br>        }<br>        throw error;<br>      })<br>      .finally(() =&gt; {<br>        refreshPromise = null;<br>      });<br>  }<br>  return refreshPromise; // concurrent callers all await the same promise<br>}</pre><p>The actual hard part isn’t the timer — it’s classifying failure. Collapsing everything into one “refresh failed → log out” branch is the single most common way this subsystem misbehaves. Not every failure means the same thing.</p><p>Two more things worth knowing before they cost you a debugging session:</p><p>Most Keycloak client libraries also run the refresh grant from inside their init call, not only from the explicit &quot;refresh now&quot; function. A dead refresh token on a freshly loaded page throws from initialization — a code path teams often forget to wrap in the same failure classifier. Miss it, and half your dead sessions never trigger a logout.</p><p>Most OIDC libraries default to auto-redirecting to the login page when a forced token refresh fails. That’s correct behavior for an interactive login flow — and exactly wrong for a silent background refresh, where it turns an expired token into the user getting bounced off whatever they were doing, mid-form, with zero warning. Disable it explicitly before a silent attempt:</p><p>javascript</p><pre>// before a silent (non-interactive) refresh<br>client.loginRequired = false;<br>await client.updateToken(-1);</pre><p>It’s a one-line fix, and it’s exactly the kind of line that disappears in a refactor because nothing about it looks load-bearing — until it’s gone.</p><h3>7. Logout: it’s two functions, not one with a flag</h3><p>Design logout as two genuinely separate paths.</p><p><strong>Voluntary</strong> — the user clicks Sign Out.</p><ol><li>Refresh tokens first if possible, so the tokens used to build the logout URL are as current as they can be.</li><li>Revoke the refresh token server-side (RFC 7009 — best-effort, don’t block the redirect waiting on it).</li><li>Clear all local state — cookies, Redux, everything.</li><li>Broadcast the logout to other tabs.</li><li>Redirect to Keycloak’s end-session endpoint.</li></ol><p><strong>Involuntary</strong> — the silent-refresh failure classifier from Section 6 decides the session is dead. This path has to be idempotent and guarded to fire exactly once — a refresh loop that keeps calling it will otherwise trigger the Keycloak redirect repeatedly.</p><p><strong>The one query parameter that isn’t optional</strong></p><p>id_token_hint on Keycloak&#39;s logout URL is how Keycloak knows which session to end without asking the user to confirm. Skip it, and per the OIDC RP-initiated logout spec, Keycloak falls back to a confirmation screen. It reads as a bug in production even though the code is, technically, spec-compliant. If a logout button ever shows a confirmation page nobody asked for, this is the first thing to check — and Section 5 above is usually why it&#39;s missing.</p><p><strong>Logout has to propagate everywhere at once</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kE0AHvMiOj0ZA19uKTZl7w.png" /></figure><p>A user with three tabs open — or a second connected app open in another tab — expects one sign-out to end all of it. That’s two separate mechanisms doing two separate jobs:</p><p>BroadcastChannel (or equivalent) handles same-origin tabs. The tab that initiated logout posts a message; every other tab&#39;s listener clears its own state and redirects. Watch for a subtle race here — BroadcastChannel delivers to listeners in the same tab too, so the initiating tab needs a guard against its own listener firing a second, competing navigation on top of the redirect already in flight.</p><p>Front-channel logout handles other apps sharing the Keycloak session. Keycloak loads a hidden iframe pointing at a route each connected app registers with it. When the shared session ends, that route fires and the app clears its own state — even though the user never touched that app’s tab.</p><pre>// route registered with Keycloak as this app&#39;s front-channel logout URL,<br>// loaded in a hidden iframe when the shared SSO session ends elsewhere<br>useEffect(() =&gt; {<br>  clearLocalSession();<br>  broadcastLogoutToOtherTabs();<br>}, []);</pre><h3>8. What this design costs — say it out loud in review</h3><p>Every SSO design is a set of trade-offs. Naming them in review beats discovering them in an incident channel.</p><p><strong>Token storage.</strong> Tokens readable by client-side JavaScript (regular cookies, or anything the app code touches directly) are necessary if the frontend itself needs to read them — but it means an XSS bug anywhere in the app is equivalent to session theft. The stronger version, when the architecture allows it, is moving the app’s own session token to an httpOnly cookie set by the backend (a BFF — Backend-for-Frontend — pattern), so client-side script never touches it even if the app is compromised. That’s real backend work, which is exactly why it deserves a line in the design doc instead of being assumed.</p><p><strong>Refresh interval.</strong> A fixed interval, rather than one derived from the token’s actual expiry claim, is a similar knowingly-simple choice — fine today, quietly wrong the day someone changes the token lifespan on the Keycloak side and forgets the frontend had it hard-coded.</p><p><strong>Middleware as a coarse gate.</strong> Validating a JWT’s expiry in edge middleware needs shared secrets, clock sync, and rotation handling — real infrastructure. Most teams reasonably defer that to the client-side interceptor and let middleware just check presence of a token cookie. The cost: a user with a technically-expired cookie can briefly flash /login before the client-side refresh catches up.</p><h3>9. The checklist — what to have an answer for before this ships</h3><ul><li><strong>Two token authorities, not one.</strong> Keycloak tokens prove identity to Keycloak; your backend issues the token your API actually trusts.</li><li><strong>Session state survives reload.</strong> Cookies are the source of truth; Redux is a cache with a fallback, never the only copy.</li><li><strong>Refresh is single-flight and correctly classified.</strong> Concurrent 401s share one refresh call. Transient failures retry. Terminal failures force logout. Both call sites that can throw a terminal failure — the explicit refresh and client init — are covered.</li><li><strong>Silent refresh can never trigger an interactive redirect.</strong> The library’s default “redirect to login on failure” is explicitly disabled for background attempts.</li><li><strong>Logout is idempotent, complete, and carries </strong><strong>id_token_hint.</strong> Guarded against firing twice, clears every local store, never builds the end-session URL without the ID token.</li><li><strong>Logout propagates everywhere.</strong> Same-tab broadcast guarded against self-triggering; front-channel logout registered for every connected app.</li><li><strong>The token-storage trade-off is a named decision.</strong> If tokens are JS-readable, that’s written down as an accepted risk, with the httpOnly + BFF alternative considered and its cost understood.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d53594325554" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>