Keycloak: stop offline sessions on mobile, use passkeys
Most mobile apps built on Keycloak keep their users signed in with an offline token (the offline_access scope) or with SSO sessions stretched to weeks. The reason is always the same: nobody wants to type a password on a phone. The cost is a credential that lives on the device for 30 days or more, survives “Sign out”, works from anywhere once it is copied, and protects an account that can still be phished.
There is a better trade-off: keep sessions short, and sign the user in again with a passkey whenever a new session is needed. One fingerprint or face scan replaces the password, so asking again costs the user almost nothing.
- User experience: no password, ever, not even at sign-up. One biometric prompt, and the user is in.
- Security: phishing-resistant by design (a passkey only works on the real domain), and a session that is closed by default: nothing long-lived stays on the phone.
We tested both approaches end to end, with Keycloak 26.8 in Docker and the exact protocol an AppAuth app uses: 22 checks, all passing. Below you will find the configuration of each realm, an AppAuth-Android sample app with one build flavor per approach, and the test results. A Going further section explains how CIBA can extend the same security level to a desktop web version of the app.
Repository: https://github.com/please-openit/passkeys-mobile-sessions
The demo runs Keycloak in dev mode onhttp://localhost:8080, withadmin/admin. Browsers treatlocalhostas a secure context, so WebAuthn works there without TLS. In production, Keycloak runs on HTTPS under your own domain, and the passkeys are bound to that domain.
Typing a password on a phone is miserable. Twelve characters with a digit and a symbol means switching between three keyboard layouts, behind a field that hides what you type. Sign-up is worse: the password goes in twice, then the strength rules reject it. Every product team that measures its funnel sees users drop off right there.
So the app makes sure the user sees that screen as rarely as possible. With Keycloak, there are two usual ways to do it:
- Offline sessions. The app asks for the
offline_accessscope and receives an offline token: a refresh token that is not tied to the browser’s SSO session and that Keycloak keeps valid for 30 days of inactivity by default, with no maximum lifespan unless you turn one on. The app stores it, and opening the app every few weeks is enough to stay signed in forever. - Very long SSO sessions. The realm’s SSO Session Idle and SSO Session Max are pushed to weeks or months, which gives the same result for every client of the realm.
Both treat the symptom (the password is painful) by making sure the user is never asked for it again. Neither addresses the password itself.
An offline token is a bearer credential: whoever holds it can get fresh access tokens. Here is what we measured on a realm with Keycloak’s default offline settings (full output in Tested for real):
=== 1. Long sessions: password + offline_access (realm long-sessions)
PASS the app gets an offline token (typ=Offline, scope="openid profile email offline_access")
PASS the offline token stays valid for 30 days without use (exp - iat = 30 days)
PASS after "Sign out" (end_session), the offline token STILL works (HTTP 200, new access token issued)
PASS a copy of the original offline token, already used by the app, still works from anywhere (HTTP 200, no cookie, no device, no rotation)
In practice:
- “Sign out” does not sign out. The OpenID Connect end-session request ends the SSO session. The offline session is a separate object and stays alive. The app has to revoke the token explicitly, and it never gets the chance when the user simply uninstalls it: the offline session then lives on, server side, until it expires.
- Nothing binds the token to the phone. A copy taken from a backup, a rooted device or a piece of malware works from any computer. Keycloak does not rotate refresh tokens by default (Revoke Refresh Token is off), so even a token the app has already used keeps working. The OAuth 2.0 Security Best Current Practice (RFC 9700) requires refresh tokens issued to public clients, which is what a mobile app is, to be either sender-constrained or rotated.
- The account is still protected by a password. The password is typed rarely, which is the whole point, but it can still be phished, reused on another site, or leaked. A long session does not make the password stronger: it makes the consequences of losing it last longer.
- Sessions pile up on the server. Every offline session is stored in Keycloak’s database and kept for weeks, one per device the user ever signed in from.
There are mitigations: a maximum lifespan for offline sessions, refresh token rotation, DPoP to bind tokens to a key held by the app. They are worth having, but they all keep a long-lived credential on the device. There is a simpler option: don’t keep one.
A passkey is a WebAuthn/FIDO2 credential: a key pair whose private key never leaves the user’s device (or their password manager, which syncs it between their devices). Signing in means unlocking it with the phone’s biometrics or PIN, and the phone signs a challenge sent by Keycloak. A passkey is bound to a domain: the browser only offers it to the site it was created for.
- Sessions are short. In the demo, 15 minutes of inactivity and 8 hours at most: about the time someone actually spends using the app. The client is not allowed to ask for
offline_accessat all. - The app keeps its tokens in memory. When the app is closed, nothing is left on the phone. When the session is over, the refresh fails and the app starts a new authorization request.
- That new authorization request is answered with a passkey: one fingerprint or face scan, no typing.
The idea behind it: what made long sessions necessary was the cost of signing in. With a passkey, signing in costs about as much as unlocking the phone, so short sessions stop being a usability problem.
| Offline token / long session | Short session + passkey | |
|---|---|---|
| Signing in | Username + password, typed on a phone | One biometric prompt |
| Signing up | Email, password twice, strength rules | Email and name, then one biometric prompt |
| What stays on the phone | A refresh token valid for 30+ days | Nothing once the app is closed |
| “Sign out” | Leaves the offline token alive | Ends the session, refresh fails |
| Stolen token | Works from anywhere until it expires | Lives for at most 15 minutes of inactivity |
| Phishing | The password can be typed on a fake page | The passkey does not work on another domain |
| Server side | One offline session per device, for weeks | Sessions expire with use |
- No password, ever. Not at sign-in, and not at sign-up either: the registration form only asks for an email and a name, then the phone creates the passkey.
- Signing in again feels like unlocking the phone. The user taps a button and looks at the screen. On a phone, that is quicker than finding the password in a password manager, let alone typing it.
- A new phone is not a new password. Passkeys synced by iCloud Keychain or Google Password Manager follow the user to their new device.
- Phishing stops working. A fake login page, even one that relays every request to the real Keycloak in real time (the adversary-in-the-middle technique used by phishing kits), sits on another domain. The browser refuses to use the passkey there, and there is no password to type. We tested exactly that: the phishing test.
- Sessions are closed by default. Long sessions are open by default and must be closed explicitly, and they rarely are. Short sessions close on their own: a lost phone, a forgotten logout or an uninstalled app all end with a session that expires within minutes.
- No password database to leak. Keycloak stores public keys. A copy of them is useless to an attacker.
Everything is in the repository: docker-compose.yml starts Keycloak 26.8.2, and setup-keycloak.sh creates one realm per approach with kcadm.sh. Both realms have the same mobile client: public, authorization code with PKCE, and the app’s custom scheme as redirect URI, as RFC 8252 (OAuth 2.0 for Native Apps) recommends.
git clone https://github.com/please-openit/passkeys-mobile-sessions.git
cd passkeys-mobile-sessions
docker compose up -d --wait
./setup-keycloak.sh
{
"clientId": "mobile-app",
"publicClient": true,
"standardFlowEnabled": true,
"directAccessGrantsEnabled": false,
"redirectUris": ["it.pleaseopen.demo:/oauth2redirect"],
"attributes": {
"pkce.code.challenge.method": "S256",
"post.logout.redirect.uris": "it.pleaseopen.demo:/oauth2redirect"
}
}
Nothing special: Keycloak’s defaults. Password sign-in, offline_access available as an optional scope of every client, offline sessions valid for 30 days of inactivity with no maximum lifespan. That is what you get when you do not change anything, which is why this anti-pattern is so common.
{
"realm": "long-sessions",
"enabled": true,
"registrationAllowed": true,
"registrationEmailAsUsername": true,
"offlineSessionIdleTimeout": 2592000,
"offlineSessionMaxLifespanEnabled": false
}
1. Short sessions and the WebAuthn passwordless policy. The passkey is bound to the Relying Party ID, which is the Keycloak domain (localhost in the demo). A discoverable credential (resident key) lets the user sign in without typing a username, and user verification (biometrics or PIN) is required.
{
"realm": "passkeys",
"enabled": true,
"registrationAllowed": true,
"registrationEmailAsUsername": true,
"rememberMe": false,
"ssoSessionIdleTimeout": 900,
"ssoSessionMaxLifespan": 28800,
"webAuthnPolicyPasswordlessRpEntityName": "please-open.it demo",
"webAuthnPolicyPasswordlessRpId": "localhost",
"webAuthnPolicyPasswordlessRequireResidentKey": "Yes",
"webAuthnPolicyPasswordlessUserVerificationRequirement": "required"
}
2. No offline token for the mobile client. Remove offline_access from the client’s optional scopes. Keycloak then refuses an authorization request that asks for it with invalid_scope, before any sign-in page is shown: a developer cannot slip it back in from the app.
client_uuid=$(kcadm get clients -r passkeys -q clientId=mobile-app --fields id --format csv --noquotes)
offline_scope=$(kcadm get client-scopes -r passkeys --fields id,name --format csv --noquotes | awk -F, '$2=="offline_access"{print $1}')
kcadm delete "clients/$client_uuid/optional-client-scopes/$offline_scope" -r passkeys
3. Sign-up without a password. Copy the built-in registration flow and disable its Password Validation step: that step is what adds the password fields to the registration form. Then make Webauthn Register Passwordless a default action, so that every new user creates a passkey right after the form.
kcadm create authentication/flows/registration/copy -r passkeys -s newName=passkey-registration
pw_exec=$(kcadm get authentication/flows/passkey-registration/executions -r passkeys --fields id,providerId --format csv --noquotes \
| awk -F, '$2=="registration-password-action"{print $1}')
kcadm update authentication/flows/passkey-registration/executions -r passkeys -b "{\"id\":\"$pw_exec\",\"requirement\":\"DISABLED\"}"
kcadm update authentication/required-actions/webauthn-register-passwordless -r passkeys \
-s enabled=true -s defaultAction=true
The result, as the user sees it: a form without any password field, then a single button.


4. Sign-in with a passkey only. A new browser flow with two alternatives: the SSO cookie, or the WebAuthn Passwordless Authenticator. No username/password form at all.
| Level | Execution | Requirement |
|---|---|---|
| 0 | Cookie | Alternative |
| 0 | passkey-forms (sub-flow) | Alternative |
| 1 | WebAuthn Passwordless Authenticator | Required |
The script builds it with kcadm (see setup-keycloak.sh), then binds both flows to the realm:
kcadm update realms/passkeys -s browserFlow=passkey-browser -s registrationFlow=passkey-registration

A passkey-only flow assumes that the user’s passkey is available: synced by their password manager, or on the phone they registered with. Plan an account recovery path for the others, for example an email link that lets them register a new passkey. Recovery is a separate, rare and well-guarded path: it should not turn into a second way to sign in every day.
AppAuth is the OpenID Foundation’s reference library for native apps (Android and iOS). It opens the authorization request in the system browser (a Custom Tab on Android, ASWebAuthenticationSession on iOS), receives the redirect on the app’s custom scheme, and exchanges the code with PKCE. Because the sign-in pages are rendered by the system browser, the passkey ceremony is plain WebAuthn on the Keycloak domain: the app has nothing to implement, and there is no Digital Asset Links or associated-domains file to publish for it.
The sample app in android-app/ is a single activity with two build flavors. Only the configuration differs:
productFlavors {
// Anti-pattern: password + offline token stored on the device for weeks
create("longSession") {
dimension = "session"
applicationIdSuffix = ".longsession"
buildConfigField("String", "REALM", "\"long-sessions\"")
buildConfigField("String", "SCOPE", "\"openid offline_access\"")
buildConfigField("boolean", "PERSIST_TOKENS", "true")
}
// Recommended: passkey, short session, nothing kept once the app is closed
create("passkey") {
dimension = "session"
applicationIdSuffix = ".passkey"
buildConfigField("String", "REALM", "\"passkeys\"")
buildConfigField("String", "SCOPE", "\"openid\"")
buildConfigField("boolean", "PERSIST_TOKENS", "false")
}
}
Storing tokens (or not). The longSession flavor writes AuthState to SharedPreferences and reloads it on startup: that is the “always signed in” app. The passkey flavor keeps it in memory only: when the process dies, the session is gone from the phone.
if (BuildConfig.PERSIST_TOKENS) {
prefs().getString("authState", null)?.let { authState = AuthState.jsonDeserialize(it) }
}
Signing up and signing in. One authorization request for both. prompt=create, defined by the OpenID Connect Initiating User Registration specification, opens Keycloak’s registration page instead of the login page. AppAuth adds PKCE and state on its own.
val request = AuthorizationRequest.Builder(config, clientId, ResponseTypeValues.CODE, redirectUri)
.setScope(BuildConfig.SCOPE)
// prompt=create opens Keycloak's registration page instead of the login page
.apply { if (signUp) setPrompt("create") }
.build() // AppAuth adds PKCE (S256) and state on its own
authLauncher.launch(authService.getAuthorizationRequestIntent(request))
When the session is over. performActionWithFreshTokens refreshes the access token while the session lives. Once Keycloak answers invalid_grant, there is no silent fallback: the app asks the user to sign in again, which takes one passkey prompt.
authState.performActionWithFreshTokens(authService) { accessToken, _, ex ->
if (ex != null) {
// Session expired or ended: no silent fallback, the user signs in again
authState = AuthState(config)
save()
return@performActionWithFreshTokens show("Session over (${ex.error}), sign in again")
}
// ... call the API with accessToken
}
Build both flavors:
cd android-app
./gradlew assembleLongSessionDebug assemblePasskeyDebug
Runadb reverse tcp:8080 tcp:8080so that the app and the browser reach Keycloak onhttp://localhost:8080: WebAuthn refuses to run onhttp://10.0.2.2, which is not a secure context. AppAuth also refuses plain HTTP by default: the sample plugs in aConnectionBuilderthat allows it, for the demo only.
On iOS, AppAuth-iOS follows the same principles. Passing prefersEphemeralSession: true to OIDExternalUserAgentIOS also discards the browser’s cookies after each sign-in, so every new session goes through the passkey. We did not build an iOS app for this article.
The script test.sh starts a fresh Keycloak, creates both realms and runs tests/run.mjs. The tests drive Chromium with Playwright and speak the same protocol as the AppAuth app: an authorization request with PKCE, a redirect to it.pleaseopen.demo:/oauth2redirect caught as the phone’s operating system would catch it, the code exchange, refresh and end-session. Each “phone” is a fresh browser context with a virtual WebAuthn platform authenticator (resident keys, user verification), driven through the Chrome DevTools Protocol. To start a new session “on the same phone”, the passkey is copied into a new context that has no cookies.
The phishing test starts a small proxy on http://127.0.0.1:8666. It forwards every request to the real Keycloak and records what goes through, as phishing kits do. Keycloak builds its URLs from the Host header, so the victim never leaves the phishing origin and sees the real Keycloak pages.
- On the long-sessions realm, the sign-in succeeds through the proxy, and the proxy now holds the password and the SSO session cookie.
- On the passkeys realm, the browser refuses to use a passkey created for
localhoston127.0.0.1. Nothing signed, nothing to steal.

=== 1. Long sessions: password + offline_access (realm long-sessions)
PASS redirect to the app carries the state it sent
PASS the app gets an offline token (typ=Offline, scope="openid profile email offline_access")
PASS the offline token stays valid for 30 days without use (exp - iat = 30 days)
PASS after "Sign out" (end_session), the offline token STILL works (HTTP 200, new access token issued)
PASS a copy of the original offline token, already used by the app, still works from anywhere (HTTP 200, no cookie, no device, no rotation)
=== 2. Passkeys: sign-up without a password (realm passkeys)
PASS the registration form has no password field (fields: email, firstName, lastName)
PASS redirect to the app carries the state it sent
PASS a passkey (discoverable credential) is now on the phone (rpId=localhost)
PASS the app gets a regular session, not an offline token (typ=Refresh)
=== 3. Passkeys: a new session = one passkey prompt
PASS asking for offline_access is refused before any sign-in page (error=invalid_scope: Invalid scopes: openid offline_access)
PASS the sign-in page has no password field
PASS redirect to the app carries the state it sent
PASS signed in as the user who registered, without typing anything (email=bob.1795449016731@example.com)
PASS a regular session again, no offline token (typ=Refresh, scope="openid profile email")
PASS the session ends after 15 minutes of inactivity (exp - iat = 15 min)
PASS while the session lives, the app refreshes its tokens silently (HTTP 200)
PASS after "Sign out", the refresh token is dead (HTTP 400 invalid_grant: Session not active)
=== 4. Adversary-in-the-middle phishing (proxy on http://127.0.0.1:8666)
PASS redirect to the app carries the state it sent
PASS password realm: the proxy captured the password (POST /realms/long-sessions/login-actions/... Correct-Horse-42)
PASS password realm: the proxy captured the SSO session cookie (KEYCLOAK_IDENTITY=eyJhbGciOiJIUzUxMiIsIn...)
PASS passkey realm: the browser refuses to use the passkey on the phishing origin (A security error occurred during the Passkey operation. Please ensure you are on the correct site and try again.)
PASS passkey realm: nothing worth stealing went through the proxy (form posted: signature="", error="SecurityError: This is an invalid domain.")
ALL CHECKS PASSED
What was not tested: the Android app is compiled (both flavors), but it was not run on a phone or an emulator. The tests cover the same protocol in Chromium, with a virtual authenticator standing in for the phone’s. On a real phone, the passkey comes from the user’s credential manager (Google Password Manager, iCloud Keychain, or a third-party one), and Keycloak runs on HTTPS under a real domain.
- Session lengths are a product decision. 15 minutes idle and 8 hours maximum fit an app used in short bursts. A banking app may want less, a note-taking app more. The point is to set lengths that match one period of use, since signing in again is cheap.
- Keep refresh tokens anyway. A short session still uses refresh tokens to renew access tokens silently while the user is active. What goes away is the token that outlives the session.
- Not every device has a passkey provider. Older phones, or users who refuse biometrics, need another way in. A PIN still unlocks a passkey, and Keycloak can offer a fallback in the flow. Decide on purpose what that fallback is, so that it does not quietly bring the password back.
- “Works offline” is a different need. An offline token does not make an app work without a network: the API still has to be reached. To protect local data in the app between sessions, use the phone’s own biometric lock (
BiometricPrompton Android,LocalAuthenticationon iOS). - Passkeys protect the sign-in, not a compromised phone. Malware running on an unlocked device can still use the session that is open. Short sessions limit how long that lasts. They do not prevent it.
Many mobile apps also have a web version that users open on their computer. That web version brings the problem back: the computer may have no passkey, or a different one, and the easy answer is a password again, plus a long session on the computer.
CIBA (Client-Initiated Backchannel Authentication, an OpenID Connect specification that Keycloak supports) offers another option: the web app delegates the authentication to the mobile app. The user types their email on the computer; the web app sends a backchannel authentication request to Keycloak; Keycloak hands it to an authentication channel that notifies the mobile app; the user approves on their phone. Only then does the web app receive its tokens.
What it brings:
- The same security level as the app on its own. The computer never handles a credential. What signs the user in is their phone and its passkey, with everything that makes them phishing-resistant.
- No password on the computer either, and the web session can be just as short, since approving on the phone takes seconds.
- A message to compare on both screens. CIBA’s
binding_messageshows the same short code on the computer and in the app, so that the user can check they are approving their own request rather than a request an attacker started at the same moment.
Implementing it in Keycloak means enabling CIBA on the web client and providing the authentication channel, an HTTP endpoint that pushes the request to the app and reports the user’s decision back to Keycloak. We described the protocol, with a client written in bash, in CIBA-bash: a bash client for the CIBA OpenID Connect protocol. This part is not implemented in the demo repository.
Is offline_access always a bad idea?
No. It was designed for clients that act on behalf of a user who is not there: a backend that synchronizes data at night, for example, and must be scoped accordingly. The anti-pattern is using it to spare a user who is there from typing a password.
Does a passkey replace the refresh token? No. The refresh token keeps the session going while the user is active. The passkey makes starting a new session cheap, which is what allows sessions to be short.
Does the mobile app need a native passkey API?
Not with AppAuth. Sign-in happens in the system browser on the Keycloak domain, so the passkey is standard WebAuthn. A native integration (Android Credential Manager, iOS ASAuthorization) would need the app and the domain to be linked through Digital Asset Links or associated domains.
Can users sign up without ever choosing a password?
Yes. Disable Password Validation in a copy of the registration flow and make Webauthn Register Passwordless a default action. The sample app opens the registration page with prompt=create.
Does Keycloak support passkeys natively? Yes. Keycloak supports WebAuthn passwordless authentication with discoverable credentials, which is what a passkey is. Everything in this article uses built-in Keycloak features, with no extension.
Offline tokens and month-long sessions are the answer to a real problem, the password on a phone, but they treat it by keeping a reusable credential on the device and a session alive on the server long after anyone needs it. With passkeys, signing in costs one biometric prompt, so the trade-off can be reversed: short sessions, closed by default, and a passkey whenever a new one is needed. Users never type a password, not even at sign-up, and phishing has nothing left to steal.
Keycloak does it with built-in features only, and AppAuth needs no change beyond not asking for offline_access. If you want to know how your realm handles sessions today, we can review it as part of a Keycloak security and configuration audit. To learn more about the flow behind AppAuth, read the authorization code flow. For a tour of the sign-in methods from the user’s side, see authentication and user experience.
Repository: https://github.com/please-openit/passkeys-mobile-sessions