Token Lifespan Configuration in Keycloak
A zero-prior-knowledge guide to every clock Keycloak keeps ticking behind a login — access tokens, refresh tokens, SSO sessions, offline sessions, and the timers that decide exactly when each one expires.
Every login you ever complete is, underneath the screen you see, the creation of a small piece of paper with an expiry date stamped on it. Log into your email, and somewhere a token is minted that says “trust this person until 10:05am.” Stay logged in for a week without retyping your password, and a completely different, longer-lived token is quietly keeping that promise alive in the background. Keycloak, the open-source identity platform used by countless companies to manage logins across all their applications, gives administrators direct control over every one of these expiry dates. This article walks through Token Lifespan Configuration in Keycloak from first principles — what each timer actually controls, how they interact, and why getting the balance wrong can either annoy every user in the company or quietly leave a stolen session valid for far longer than it should be.
Foundations
Core Concepts
Before touching any settings screen, it helps to understand what a “token” and a “session” actually are, and why Keycloak needs several different lifespans instead of just one.
What is a token?
When you log into an application protected by Keycloak, you do not hand your password to that application directly. Instead, Keycloak verifies your identity once and then issues small, digitally signed pieces of data called tokens. A token is essentially a tamper-proof note that says “this specific person was verified, they are allowed to do these specific things, and this note stops being valid at this specific time.” The application trusts the token because it trusts Keycloak’s digital signature on it, without needing to ask Keycloak to re-check every single request.
What is a session?
A session is the underlying record, kept on Keycloak’s server, that represents your ongoing logged-in state. Tokens are short-lived proof documents handed out repeatedly during a session’s lifetime; the session itself is the longer-running relationship between you and Keycloak that those tokens are drawn from. You can think of the session as a hotel guest’s reservation and each token as a fresh room key card issued during that stay — the reservation might last three nights, but the key card itself might need to be reissued or expire after just a few hours for security reasons.
Picture a large office building where visitors get a temporary badge at the front desk. The badge itself might only work for two hours before it needs to be scanned again at the desk to stay active — that is like an access token. But your name stays on the building’s guest list for the entire day even if your badge needs periodic re-scanning — that is like the underlying session. And if you leave the building and come back a week later without ever checking out, the guest list eventually forgets you entirely — that is like a session’s maximum lifespan.
Why so many different timers?
A single expiry setting cannot serve every purpose at once, because different pieces of the login system carry very different levels of risk and are used in very different ways. A token that travels with every single web request needs to expire quickly, because if it is ever stolen, a short lifespan limits the damage. A session that represents “please don’t make me log in again while I’m actively working” needs to last much longer, because forcing a password re-entry every few minutes would make the software unusable. Keycloak solves this by giving administrators separate, independently configurable lifespans for access tokens, refresh tokens, browser sessions, client sessions, offline sessions, and several supporting timers, each tuned to its own purpose.
Access Token
The proof-of-identity document sent with every API request. Deliberately short so a stolen copy has little value.
Refresh Token
Used behind the scenes to quietly obtain a new access token without asking the user to log in again.
SSO Session
The overall “you are logged in” state shared across every application connected to the same realm.
Offline Session
Designed for apps and devices that need continued access even when the user is not actively browsing.
Structure
Architecture & Components
Keycloak organizes its timers into a small number of settings groups, each living in a specific part of the admin console, each affecting a different layer of the login experience.
Realm-level Tokens tab
The primary home for lifespan configuration is the realm’s Tokens settings tab. Every setting here applies realm-wide by default, meaning it governs every application connected to that realm unless a specific client overrides it. This is where administrators set the Access Token Lifespan, the SSO Session Idle and Max timeouts, the Client Session Idle and Max timeouts, the Offline Session Idle and Max timeouts, and several supporting values like the Access Code Lifespan used during the login process itself.
Client-level overrides
Because different applications connected to the same realm can have very different risk profiles, Keycloak allows individual clients — the technical term for a registered application — to override certain realm-wide session timers with their own values. A highly sensitive internal finance tool might set a much shorter session timeout than the general employee intranet, even though both applications share the same realm and the same underlying users.
The token types themselves
Keycloak issues several distinct token types during a typical login, each carrying its own signature and its own expiry, encoded as a standard called JWT (JSON Web Token). The ID Token tells an application who the user is. The Access Token is presented to protected resources and APIs as proof of an authorized request. The Refresh Token is presented only back to Keycloak itself, in exchange for a fresh Access Token, without requiring the user to log in again.
flowchart TD
A["User logs in once"] --> B["Keycloak creates an SSO Session"]
B --> C["Access Token issued: short lifespan"]
B --> D["Refresh Token issued: medium lifespan"]
C -->|"Expires quickly"| E["Application uses Refresh Token"]
E --> F["Keycloak checks SSO Session still valid"]
F -->|"Session alive"| G["New Access Token issued"]
F -->|"Session expired"| H["User must log in again"]
B --- I["Client Session: per-application timers"]
B --- J["Offline Session: for background/device access"]
Fig 1 — How the SSO Session sits underneath and governs the shorter-lived Access and Refresh Tokens.
Notice that the Access Token and Refresh Token are both, in a sense, disposable — they are reissued constantly during a login’s lifetime. The SSO Session is the more stable anchor underneath them, and its own expiry ultimately decides how long a user can keep quietly refreshing tokens before being forced to log in again from scratch.
Each lifespan setting is not just a single number — it is a rule that Keycloak’s server actively enforces every time a token or session is checked.
How Access Token Lifespan works
When Keycloak issues an Access Token, it stamps an expiry timestamp directly inside the token’s signed contents. Applications that receive this token can check the expiry themselves, without even calling back to Keycloak, because the timestamp is cryptographically protected against tampering. Once that timestamp passes, any attempt to use the token for a protected request should be rejected by a properly built application, even if the token is otherwise perfectly valid.
SSO Session Idle vs SSO Session Max
These two settings are frequently confused, but they measure completely different things. SSO Session Idle measures inactivity — if the user does not interact with any connected application for longer than this period, the session is closed automatically, even if the overall session is nowhere near its maximum age. SSO Session Max is a hard ceiling on total session age, counted from the moment of login, regardless of how actively the user has been using the applications in between. A session is always closed by whichever of the two limits is reached first.
Think of a library study room booking. “Idle timeout” is like the room being automatically released if no one has badged in or out for two hours, even mid-afternoon. “Max timeout” is like the booking simply ending at closing time no matter how continuously the room was used throughout the day. Whichever limit arrives first ends the booking.
Client Session Idle and Max
Client Sessions work almost identically to SSO Sessions but at a finer level of detail, tracking the relationship between the user and one specific application rather than the whole realm. In most default configurations, these values are set equal to or shorter than the SSO Session values, since a per-application session cannot meaningfully outlive the broader login it depends on.
Offline Session Idle and Max
Offline sessions exist for a different problem entirely: applications, background jobs, or devices that need continued access to a user’s data even while the user is not actively browsing — a mobile app syncing overnight, or a background integration pulling calendar events. Offline sessions rely on a special, long-lived Offline Refresh Token that remains valid across the Offline Session Idle and Max windows, which are typically configured to be far longer than ordinary browser session timers, sometimes measured in days or weeks rather than minutes or hours.
Access Code Lifespan and Action Token Lifespans
A handful of smaller, supporting timers round out the picture. The Access Code Lifespan controls how long a user has to complete the login process itself — entering credentials, completing a second factor — before the login attempt times out and must restart. Action Token lifespans separately govern short-lived, single-purpose links Keycloak emails to users, such as email verification links or password reset links, each with its own independent expiry appropriate to how that link will actually be used.
Lifecycle
Data Flow & Lifecycle
Watching a single user’s day unfold shows exactly when each timer is checked, refreshed, or allowed to expire.
Morning login
The user enters their password once. Keycloak creates a brand-new SSO Session and Client Session, and immediately issues an Access Token and a Refresh Token, each stamped with its own expiry based on the realm’s configured lifespans.
Active work continues
Every few minutes, as the Access Token approaches its short expiry, the application silently exchanges the Refresh Token for a new Access Token in the background. The user notices nothing; the SSO Session Idle clock resets with every one of these interactions.
Lunch break
The user steps away from their desk. No refresh requests happen during this time, so the SSO Session Idle timer keeps counting upward, uninterrupted, toward its configured limit.
Return from lunch — inside the idle window
If the break was shorter than the SSO Session Idle setting, the very next request quietly refreshes the tokens and resets the idle clock again, with no visible interruption to the user at all.
Return from a long absence — idle timeout exceeded
If instead the user was away longer than the SSO Session Idle setting, Keycloak has already closed the session. The next request fails the refresh attempt, and the application redirects the user back to the login page.
End of the configured maximum
Even for a user who never once steps away, staying continuously active past the SSO Session Max setting eventually forces a fresh login regardless, since the maximum lifespan is a hard ceiling independent of activity.
Weighing the Choice
Advantages, Disadvantages & Trade-offs
Every lifespan setting is a dial between two opposing forces: user convenience on one side, and blast radius from a stolen token or session on the other.
Advantages of Short Lifespans
- A stolen Access Token becomes worthless within minutes, drastically limiting the damage of a leaked token
- Revoked permissions and role changes propagate to users far faster, since old tokens expire quickly and get replaced with freshly evaluated ones
- Reduces the value of a compromised device to an attacker, since long-term unattended access is harder to maintain
- Encourages a healthier overall security posture by forcing periodic re-validation of the user’s identity
Disadvantages of Short Lifespans
- More frequent token refresh traffic between applications and Keycloak, adding a small amount of ongoing server load
- Users on flaky or slow networks may experience more frequent forced re-logins if a refresh attempt fails at the wrong moment
- Poorly built applications that do not implement silent token refresh correctly will interrupt users far more often
- Very short session idle timeouts can frustrate users who read, think, or step away between actions without truly abandoning their work
Finding the right balance per application
There is no single “correct” lifespan that fits every situation, which is exactly why Keycloak allows client-level overrides. A public-facing marketing portal with low-sensitivity content can comfortably tolerate long, generous session timeouts that keep users logged in for days. A system that can move money or expose confidential records benefits from far shorter Access Token lifespans and tighter SSO Session Idle windows, even at the cost of slightly more friction for legitimate users, because the value of what a stolen token could reach is so much higher.
Defense
Security
Token lifespan settings are, at their core, a security control — they define exactly how long a compromise, once it happens, continues to matter.
Limiting the blast radius of a stolen token
If an Access Token leaks — through a logging mistake, a browser extension, or a network interception — its usefulness to an attacker is capped entirely by its expiry. A five-minute Access Token lifespan means a leaked token is only dangerous for, at most, five minutes. This single design choice is one of the most effective, low-effort security wins available in the entire system, because it requires no user behavior change at all.
Revocation and its limits
Keycloak also supports actively revoking sessions and tokens before their natural expiry — for example, an administrator forcing a specific user to log out everywhere immediately after a suspected compromise. However, because Access Tokens are self-contained and independently verifiable by applications, a revoked session does not instantly invalidate an Access Token that was already issued and has not yet expired, unless the application specifically checks token validity against Keycloak on every request rather than only checking the signature locally. This is precisely why keeping Access Token lifespans short matters even when active revocation capabilities exist.
Many teams assume that revoking a session in the admin console immediately kills every token tied to it. In reality, an already-issued Access Token can remain technically usable, purely by its own embedded expiry, until that timestamp is reached — revocation mainly stops future refreshes and new logins. Short Access Token lifespans are what actually bound this gap.
Offline sessions as an extended attack surface
Because Offline Sessions are intentionally long-lived, an Offline Refresh Token that leaks carries far more risk than an ordinary one, sometimes remaining usable for weeks. Deployments that grant offline access should scope it carefully to only the applications and users that genuinely need background access, and should monitor offline session usage as closely as any other high-privilege credential.
Remember-me and its own separate timer
Keycloak provides a distinct, typically longer, “SSO Session Idle — Remember Me” setting for users who explicitly opt to stay logged in for extended periods on a trusted device. Because this setting deliberately extends the idle window well beyond the default, it should be evaluated with the same care as any other long-lived credential, particularly on realms where users might check this option on shared or public computers.
Visibility
Monitoring, Logging & Metrics
Lifespan settings are only as good as the visibility an organization has into how sessions and tokens actually behave once real users start logging in.
Session monitoring in the admin console
Keycloak’s admin console provides a live view of active sessions per client and per realm, letting administrators see exactly how many users currently hold valid sessions, and allowing individual sessions to be revoked manually when necessary — for example, during an employee offboarding or a suspected account compromise.
What to watch for in the event logs
Keycloak’s event logging system records login, refresh token, and logout activity, which becomes valuable once patterns are examined over time. An unusually high volume of refresh token failures across many users at once often indicates a lifespan setting that is too aggressive for real-world usage patterns, generating more forced re-logins than intended. Conversely, sessions that remain active for unexpectedly long periods can reveal a maximum lifespan that was configured far more generously than the organization’s security policy actually intended.
Capacity planning around session storage
Every active session and offline session Keycloak tracks consumes server-side storage and processing resources. Realms with very long session lifespans and large numbers of concurrent users should monitor the underlying session store’s size and performance, since an overly generous set of lifespans across a large user base can meaningfully increase infrastructure load compared to a tighter configuration.
Shape
Design Patterns & Anti-patterns
The way an organization structures its lifespans across realms and clients reveals a lot about how carefully it has thought through its actual risk profile.
Pattern: Tiered lifespans by sensitivity
Mature deployments rarely use one set of lifespans for everything. Instead, low-sensitivity internal tools get generous, user-friendly session lengths, while high-sensitivity applications — payment systems, admin consoles, HR records — receive client-level overrides with much shorter Access Token and SSO Session Idle values, even though every application shares the same underlying realm and user base.
Pattern: Short access tokens, longer refresh cycle
A widely adopted pattern keeps the Access Token Lifespan very short — often just a few minutes — while allowing the SSO Session, and therefore the practical ability to keep refreshing, to last much longer. This gives the best of both worlds: minimal exposure if a single Access Token leaks, combined with a login experience that does not constantly interrupt genuinely active users.
Pattern: Separate offline access grants
Rather than raising the general SSO Session Max realm-wide just to accommodate one background-syncing mobile app, well-designed deployments grant that specific application Offline Access separately, keeping the everyday browser session timers tight while still supporting the one legitimate long-running use case.
Anti-pattern: One giant lifespan for everything
A common mistake is setting every timer to the same generously long value across the entire realm simply to avoid dealing with user complaints about being logged out. This approach quietly maximizes the blast radius of every future token or session leak across every connected application, regardless of how sensitive that particular application actually is.
Situation
Users complain about being logged out too often, so an administrator raises the realm’s SSO Session Idle and Max values dramatically, applying the change to every connected application at once.
Consequence
The organization’s most sensitive internal tools — previously protected by short-lived sessions — now inherit the same extended lifespans as the low-risk employee intranet, silently widening the window of exposure for a stolen laptop or a shared, unattended workstation.
Better Approach
Diagnose which specific applications are generating the complaints, and adjust client-level session overrides only for those lower-risk applications, leaving realm defaults and sensitive-application overrides untouched.
Getting It Right
Best Practices & Common Mistakes
A handful of practical habits separate a lifespan configuration that quietly protects the organization from one that either annoys everyone or protects no one.
Keep Access Tokens short
A few minutes is usually enough. Rely on the Refresh Token and a healthy SSO Session to carry the actual user experience without forcing repeated logins.
Override at the client level for sensitive apps
Do not force every application to live under the same realm-wide defaults when their risk profiles are clearly different.
Scope offline access narrowly
Only grant Offline Access to the specific applications that genuinely need background operation, never as a realm-wide default.
Review lifespans against real usage data
Use session and event monitoring to tune idle and max timeouts based on how people actually work, not guesswork.
Confusing idle and max timeouts
Raising the wrong one while trying to fix a user complaint often produces the opposite of the intended effect.
Ignoring the “Remember Me” timer
Leaving this separate, longer idle setting at a very generous default on realms accessed from shared or public devices quietly reintroduces risk the shorter default was designed to prevent.
Whenever a lifespan value is changed, document why — which risk or complaint it was addressing — directly alongside the realm’s configuration notes. Session timers are exactly the kind of setting that quietly drifts upward over years of one-off complaint fixes unless each change is deliberately recorded and periodically reviewed.
In Practice
Real-World & Industry Examples
Token lifespan tuning shows up differently depending on the kind of organization and the kind of application sitting behind Keycloak.
Financial services
Banking and payment platforms are frequently the most aggressive about short lifespans, commonly running Access Tokens that expire in a small number of minutes and SSO Session Idle windows measured in single-digit minutes for the most sensitive transaction screens, accepting the added friction as the cost of protecting accounts that can move real money.
Enterprise productivity suites
Large organizations running internal productivity tools behind a shared Keycloak realm typically favor longer SSO Session Max values — often spanning a full working day or more — paired with short Access Token lifespans, so that employees are not repeatedly interrupted during normal work while a leaked in-flight token still expires quickly.
Mobile applications and IoT integrations
Mobile apps and connected-device integrations that need to function even without the user actively present rely heavily on Offline Access and its correspondingly longer Offline Session Idle and Max values, since forcing a mobile user to fully re-authenticate every few minutes for background notifications or syncing would make the application impractical to use.
Public-sector and healthcare portals
Portals handling citizen or patient data commonly set relatively short SSO Session Idle timeouts specifically to reduce the risk of an unattended, still-logged-in session on a shared kiosk or clinical workstation, even while allowing a longer SSO Session Max for users who remain continuously active throughout a legitimate single visit.
Questions Answered
FAQ
Wrapping Up
Summary & Key Takeaways
Token Lifespan Configuration in Keycloak is ultimately a set of dials that decide how long trust, once granted, keeps being honored. Access Tokens are deliberately short-lived proof documents, refreshed constantly behind the scenes by longer-running sessions that decide the real shape of the user’s day-to-day experience. Every one of these timers — Access Token, Refresh Token, SSO Session Idle and Max, Client Session Idle and Max, Offline Session Idle and Max, Access Code Lifespan, and Action Token lifespans — exists to answer the same underlying question for a different slice of the system: exactly how long should this particular piece of trust remain valid before it must be earned again?
Key Takeaways
- Tokens and sessions are different things — tokens are short-lived proof documents, while sessions are the longer-running logged-in relationship they are drawn from.
- Idle and Max timeouts measure different things — idle tracks inactivity, max is a hard ceiling on total age, and whichever is reached first ends the session.
- Short Access Token lifespans are one of the cheapest, most effective security wins available — they cap the damage of a leaked token without requiring any change in user behavior.
- Client-level overrides let sensitive applications live under stricter rules — without forcing the same friction onto every low-risk application in the realm.
- Offline sessions solve a genuinely different problem — background and device access — and deserve their own careful, narrowly scoped configuration.
- Session revocation has limits — an already-issued Access Token can outlive a revoked session until its own expiry, which is exactly why short lifespans still matter.
- Every lifespan change should be deliberate and documented — these settings tend to drift toward convenience over time unless someone is actively watching the trade-off.